【发布时间】:2016-09-29 11:37:14
【问题描述】:
我有一个父组件,它有一个title 字段。使用 @input 装饰器将此字段传递给子组件。在我的子组件中,我添加了一些逻辑来操作 title 值,然后再将其显示在我的 HTML 中。
因为我的逻辑在子组件的ngInit钩子里,所以只有title字段第一次正确反映。从那时起发生的变化不会反映。现在我知道这是因为 ngInit 被调用了一次,但是我如何触发从我的父母到孩子的变化告诉它重新检查值?
编辑添加代码 sn-p
标头(子)组件
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>
【问题讨论】:
-
提供一些代码 sn-p 或创建一个 plunker/jsfiddle。
标签: angular typescript