2017-04-26 82 views
11

我很困惑。何時在指令@Inputs和不指定時使用方括號[]?

看到這個簡單的指令:

@Directive({ 
     selector: '[myDirective]' 
    }) 
    export class MyDirective { 

     private text: string; 
     private enabled: boolean; 

     @Input() myDirective:string; 

     @Input('myText') 
     set myText(val: string) { 
     this.text = val; 
     } 

     @Input('myEnabled') 
     set myEnabled(val: boolean) { 
     this.enabled = val; 
     } 

     ngOnInit() { 

     console.log("myDirective string: " + this.myDirective); 
     console.log("myText string: " + this.text); 
     console.log("myEnabled boolean: " + this.enabled); 
    } 
} 

如果我的HTML看起來像這樣:

<div [myDirective]="myDefaultText" [myEnabled]="true" [myText]="abc"></div> 

輸出將是:

myDirective string: myDefaultText real value // good 
myEnabled boolean: true      // good 
myText string: undefined      // Why? 

如果我刪除[]從myText

<div [myDirective]="myDefaultText" [myEnabled]="true" myText="abc"></div> 

輸出將是:

myDirective string: myDefaultText real value // good 
myEnabled boolean: true      // good 
myText string: abc       // GOOD 

我也可以刪除myEnabled[],它也能工作。 所以這裏是我的困惑 - 當我需要使用方括號[],當沒有,當我想要使用myDirective的用戶將永遠不需要懷疑是否如果不,我認爲方括號[]應該總是在那裏。他們不是嗎?

回答

10

當您使用[]綁定到@Input()時,它基本上是一個模板表達式。

與顯示{{abc}}相同的方式不會顯示任何東西(除非您實際上有一個名爲abc的變量)。

如果你有一個字符串@Input(),並希望將其綁定到一個常量字符串,你可以結合這樣的:[myText]=" 'some text' ",或短,像一個正常的HTML屬性:myText="some text"

原因[myEnabled]="true"工作是因爲true是一個有效的模板表達式,當然這個模板表達式的計算結果爲布爾值true

+1

我甚至都不認爲這就是實際發生的事情,你確定嗎?提問者提到'[myDirective] =「myDefaultText」給出了輸入「myDefaultText real ** value **」,雖然他的意思是myDefaultText的實際值,這意味着它仍然被當作一個表達式。 – Amit

+1

我錯了。錯過了「真正的價值」。 –

+2

在[本頁](https://angular.io/guide/template-syntax#one-time-string-initialization)上的當前的Angular 4文檔中介紹了這一點。 – 2Aguy

6

括號告訴Angular評估模板表達式。如果省略方括號,Angular會將該字符串視爲常量並使用該字符串初始化目標屬性。它不評估字符串!

不要讓下面的錯誤:

<!-- ERROR: HeroDetailComponent.hero expects a 
     Hero object, not the string "currentHero" --> 
    <hero-detail hero="currentHero"></hero-detail> 

檢查:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#property-binding

2

結合[]爲對象,如果沒有它的值是字符串。請注意類型。

在代碼

<div [myDirective]="myDefaultText" [myEnabled]="true" [myText]="abc"></div> 

你已經嘗試了對象綁定,但對象是不可用的,因此它的價值是undefined。另一方面,如果您刪除了綁定,那麼該對象不見了,您只有一個string值分配給該屬性。

+1

確保不要執行'myEnabled =「false」'因爲這會被評估爲一個字符串,因爲'「false」'實際上是一個真值,它不會像你期望的那樣行爲。 –

+0

你從哪裏看到的? –

相關問題