Template property is undefined while others are?

2019-09-20 04:37发布

问题:

I'm trying to define a simple component, with several properties :

randomFile.html :

<dico [dicoID]="201125" [dicoLang]="en" [delayedLoading]="false"></dico>
<dico [dicoID]="201126" [dicoLang]="en" [delayedLoading]="false"></dico>

Here is my component definition :

dico.component.ts :

@Component({
    selector: 'dico',
    template: `{{text}}`
})

class Dico implements AfterViewInit {
    @Input() private dicoID: string;
    @Input() private dicoLang: string;
    @Input() private delayedLoading :boolean;
    public text: string = null;

    constructor(...) {
    }

    ngAfterViewInit() {
        alert(this.dicoID + " " + this.dicoLang + " " + this.delayedLoading);

        // Output 1 => 201125 undefined false 
        // Output 2 => 201126 undefined false 
        (...)
    }

    (...)
}

----

@Component({
    template: `<dico [dicoID] [dicoLang] [delayedLoading]></dico>`,
    directives: [Dico]
})

// Définition du composant DicoComponent
export class DicoComponent {

}  

As you can see in the ngAfterViewInit, the second property "dicoLang" is undefined, and I don't understand why... Am I doing something wrong ?

回答1:

If you want to directly pass values inside property binding you should do use attribute instead of property binding. If you wrap your attribute with [] (property binding), it will try to evaluate that variable with Component context(this).

<dico dicoID="201125" dicoLang="en" [delayedLoading]="false"></dico>
<dico dicoID="201126" dicoLang="en" [delayedLoading]="false"></dico>


回答2:

Binding with []-brackets implies binding to a variable or a static expression. Numbers and boolean values are static expressions in itself, so the binding works as intended. But if you just write [dicoLang]="en", it expects a variable called 'en'.

You could either bind with an explicit string:

<dico [dicoID]="201125" [dicoLang]="'en'" [delayedLoading]="false"></dico>
<dico [dicoID]="201126" [dicoLang]="'en'" [delayedLoading]="false"></dico>

Or bind without the brackets:

<dico [dicoID]="201125" dicoLang="en" [delayedLoading]="false"></dico>
<dico [dicoID]="201126" dicoLang="en" [delayedLoading]="false"></dico>