2017-09-25 57 views
0

我們在Angular 2中有一個自定義輸入組件。什麼是向我們的自定義組件添加屬性的正確方法?我們輸入組件的要點就是這樣。將屬性添加到自定義Angular 2組件的正確方法

輸入debounce.component.ts

var template = ` 
    <input 
    [type]="inputType" 
    [placeholder]="placeholder"> 
`; 

@Component({ 
    selector: "input-debounce" 
    template: template 
}) 

export class InputDebounceComponent { 
    @Input() inputType: string = "text"; 
    @Input() placeholder: string = ""; 
} 

什麼是一個aria-label屬性添加到自定義組件的正確方法?

<input-debounce 
    [inputType]="'number'" 
    [placeholder]="'Enter Number'" 
    [attr.aria-label]="'Age'"> 
</input-debounce> 

或在類中添加的template[aria-label]="ariaLabel",並@Input() ariaLabel = "";,然後使用自定義組件時這樣稱呼它[ariaLabel]="'Age'"

當我這樣做了第二種方式,Window的講述人宣佈我放入的詠歎調標籤,但第一種方式,它什麼也沒說。

回答

1

按照該docs,你可以在任何HTML元素上使用aria-label,但它並不像你第一次嘗試,attr.aria-label定製角元素所用的方式工作(因爲屬性attr未在此規定您創建的自定義元素)。在第二種方法中,您基本上通過@Input屬性將aria-label的值傳遞給自定義元素<input-debounce>,並按docs中所述正確分配給屬性aria-label(您不必初始化您通過的屬性的值作爲組件中的@Input,因爲它已經從父模板獲得了賦值給它的值)。

// this declaration below 
// @Input() ariaLabel = ""; 
// can be changed to 
@Input() ariaLabel: string; 

這同樣適用於其他2 @input聲明以及他們已經越來越通過輸入屬性(特性)傳遞的值。你只需要指定它的type,'string'(或其它),就像ariaLabel一樣。用於設置aria-label(此處爲ariaLabel)的@Input屬性名稱只要在組件的模板中正確分配給aria-label屬性即可。

泛化,你可以聲明(任意)自定義輸入屬性名稱,說customForAriaLabel,並通過它來進行這樣的組件模板中使用的值,

父模板

<input-debounce 
    [inputType]="'number'" 
    [placeholder]="'Enter Number'" 
    [customForAriaLabel]="'Age'"> 
</input-debounce> 

自定義組件與其模板

var template = ` 
    <input 
    [type]="inputType" 
    [placeholder]="placeholder" 
    [aria-label]="customForAriaLabel"> 
`; 

@Component({ 
    selector: "input-debounce" 
    template: template 
}) 

export class InputDebounceComponent { 
    @Input() inputType: string; 
    @Input() placeholder: string; 
    @Input() customForAriaLabel: string; 
} 

希望這是有道理的。

+0

是的,這是有道理的!這也是我解決問題的方式(使用第二種方式)。但是在Angular經驗的團隊中有人提出了讓我感到困惑的第一種方式,因爲我對Angular還是一個新手。我只是想確認我的理解:因爲它是一個自定義組件,所以不能簡單地添加綁定到它的屬性,是正確的並且不會發瘋! – midnightnoir

相關問題