Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从父组件更新子组件输入的角度_Javascript_Angular - Fatal编程技术网

Javascript 从父组件更新子组件输入的角度

Javascript 从父组件更新子组件输入的角度,javascript,angular,Javascript,Angular,如果更改检测设置为OnPush,如何从父组件启动子组件的更改检测?对象数组在父组件中维护,对于我的情况,对子值(数组中的项)的更改是从父组件启动的 app.component.html: <ul> <li *ngFor="let item of items"> <button mat-button (click)="onClickMe(item)">Basic</button> <h

如果更改检测设置为OnPush,如何从父组件启动子组件的更改检测?对象数组在父组件中维护,对于我的情况,对子值(数组中的项)的更改是从父组件启动的

app.component.html:

<ul>
  <li *ngFor="let item of items">
    <button mat-button (click)="onClickMe(item)">Basic</button>
    <hello [item]=item></hello>
  </li>
</ul>
    基本的
app.component.ts(相关部分):

导出类AppComponent{
项目:项目[]=[];
构造函数(){
设i:number=0;

对于(i=0;iOnPush意味着检查引用,而不是值。除非父级开始将
的新引用传递给子级,否则不会在子级中跟踪任何内容。处理此问题的一种方法是更改
onClickMe
函数,这样它就开始修改
值,而不是修改
项在那里注入一个新对象,如下所示:

<button mat-button (click)="onClickMe(i)">Basic</button>

// in .ts
onClickMe(i: number): void {
  const item = this.items[i];
  this.items[i] = { ...item };
  // you can do this in-place now, as a new reference is already created
  this.items[i].tmps[0].selected = !this.items[i].tmps[0].selected;
  console.log(item.tmps[0].selected);
}
Basic
//in.ts
onClickMe(i:编号):无效{
const item=this.items[i];
this.items[i]={…item};
//现在可以就地执行此操作,因为已经创建了一个新引用
this.items[i].tmps[0]。选中=!this.items[i].tmps[0]。选中;
console.log(item.tmps[0]。选中);
}

您需要将新对象传递给子对象。OnPush意味着如果子对象具有相同的对象(通过引用),它将不会执行检测。如何将新对象传递给子对象?它是通过模板传递的。
@Component({
  selector: 'hello',
  template: `
    <h1>{{item.id}} - {{item.name}}</h1>
    <li *ngFor="let tmp of item.tmps">
    {{tmp.value}} - {{tmp.selected}}
    </li>
  `,
  styles: [`h1 { font-family: Lato; }`],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent {

  @Input() item: Item;

}
<button mat-button (click)="onClickMe(i)">Basic</button>

// in .ts
onClickMe(i: number): void {
  const item = this.items[i];
  this.items[i] = { ...item };
  // you can do this in-place now, as a new reference is already created
  this.items[i].tmps[0].selected = !this.items[i].tmps[0].selected;
  console.log(item.tmps[0].selected);
}