如何使用@input decorator angular 2

时间:2016-09-29 11:37:14

标签: angular typescript

我有一个父组件,其中包含title字段。使用@input装饰器将此字段传递给子组件。在我的子组件中,我添加了一些逻辑来操作title值,然后在我的HTML中显示它。

因为我的逻辑位于子组件的ngInit挂钩中,所以只有第一次正确反映title字段。从那时起发生的变化并未反映出来。现在我知道这是因为ngInit被调用了一次,但我如何触发从父母到孩子的更改,告诉它重新检查该值?

编辑添加了代码段

标题(子)组件

export class HeaderComponent implements OnInit {
@Input() title: string | Array<any>;

titleType = 'string';
tabletTitle: string | Array<any>;


constructor() { }

ngOnInit() {

    if ( typeof this.title == 'object' ) {
        this.titleType = 'array';

        // For tablet - only send the last most array item
        this.tabletTitle = [this.title[this.title.length - 1]];     // Has to be in the form of array (to be consistent with other orange header data type)
    } else {
        // Title is string - same for tablet
        this.tabletTitle = this.title;
    }

    // Temporary to show filter button on catalog page
    if ( this.page == 'catalog' ) {
        this.showFilterButton = true;
    }
}
}

标题模板

    <h1 *ngIf="titleType=='string'">{{title}}</h1>
    <h1 *ngIf="titleType=='array'">
        <ul class="header-breadcrumb">
            <template ngFor let-item [ngForOf]="title | keyValueObject">
                <li title="{{item.value['title']}}">
                    <a *ngIf="item.value['link']" [routerLink]="item.value['link']">{{item.value['title']}}</a>
                    <span *ngIf="!item.value['link']">{{item.value['title']}}</span>
                </li>
                <li *ngIf="!last" class="separator"></li>
            </template>
        </ul>
        <ul class="header-breadcrumb tablet">
            <li *ngFor="let item of tabletTitle | keyValueObject">
                <a *ngIf="item.value['link']" [routerLink]="item.value['link']">{{item.value['title']}}</a>
                <span *ngIf="!item.value['link']">{{item.value['title']}}</span>
            </li>
        </ul>
    </h1>

父组件

if ( this.parentCatId ) {
    // Push Parent Category name in header title
    this.headerTitle.push({title: 'Parent'});
}

if ( this.subCatId ) {          
    // Push Sub Category name in header title
    this.headerTitle.push({title: 'Child'});
}

父组件HTML

<app-header [title]="headerTitle"></app-header>

1 个答案:

答案 0 :(得分:9)

您可以将@Input() title: string | Array<any>设置为设置者,也可以使用ngOnChanges()代替ngOnInit()。每次ngOnChanges()更新时都会调用@Input()

@Input() set title(value: string | Array<any>) {
  ...
}

ngOnChanges() {

    if ( typeof this.title == 'object' ) {
        this.titleType = 'array';

        // For tablet - only send the last most array item
        this.tabletTitle = [this.title[this.title.length - 1]];     // Has to be in the form of array (to be consistent with other orange header data type)
    } else {
        // Title is string - same for tablet
        this.tabletTitle = this.title;
    }

    // Temporary to show filter button on catalog page
    if ( this.page == 'catalog' ) {
        this.showFilterButton = true;
    }
}