Template property is undefined while others are?

笑着哭i 提交于 2019-12-13 10:18:17

问题


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>


来源:https://stackoverflow.com/questions/39393292/template-property-is-undefined-while-others-are

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!