Angular2:如果值没有改变,输入设置器不会拾取设置事件

前端之家收集整理的这篇文章主要介绍了Angular2:如果值没有改变,输入设置器不会拾取设置事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在这里参考Angular2文档文件:[ https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter](Parent to child setter),我有以下子组件代码

import { Component,Input } from '@angular/core';
@Component({
  selector: 'name-child',template: '<h3>"{{name}}"</h3>'
})
export class NameChildComponent {
  private _name = '';
  @Input()
  set name(name: string) {
    console.log("name change");
    this._name =  name;
  }
  get name(): string { return this._name; }
}

父母很简单:

import { Component } from '@angular/core';
@Component({
  selector: 'name-parent',template: `
  <h2>Parent </h2>
  <name-child [name]="name"></name-child>
  `
})
export class NameParentComponent {
   // somewhere on ngOnInit,set name without changing value
    ngOnInit() { 

        // get pending paged only and so on
        setTimeout(() => {
            this.name = "a";
            setTimeout(() => {
                this.name = "a";
                setTimeout(() => {
                    this.name = "a";
                },1000);

            },1000);

        },1000);
   }
}

您希望控制台在3秒内三次注销“名称更改”.它没有,它记录一次,并忽略后续集(只有在值没有改变时才会发生这种情况).无论值是否发生变化,如何使输入选择设置事件?

解决方法

我看到两种解决方法

1)使用不可变值

setTimeout(() => {
  this.name = new String("a");
    setTimeout(() => {
      this.name =  new String("a");
      setTimeout(() => {
       this.name =  new String("a");
    },1000);
  },1000);
},1000);

2)直接更改输入属性

@ViewChild(NameChildComponent) child: NameChildComponent;

setTimeout(() => {
  this.child.name = "a";
  setTimeout(() => {
    this.child.name = "a";
    setTimeout(() => {
      this.child.name = "a";
    },1000);

猜你在找的Angularjs相关文章