角度输入属性,看来我无法多次重新分配它

时间:2019-03-21 12:46:40

标签: angular

我正在使用Angular7。并且我有意外的行为。

父组件代码:

 parcial_result:boolean = false;

 fetchData(): void {
   this.parcial_result = true;
 }


....
<app-window [visible]="parcial_result"></app-window>

从服务器获取一些数据后,通过将parcial_result属性设置为true来显示组件。

我的孩子部分

@Input() visible: boolean = true;

constructor(private eRef: ElementRef) { }

  @HostListener('document:click', ['$event'])
    //if the user clicks outside this component I hide it again.

  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {

    } else {
     this.visible = false; //as soon this code executes I cannnot set visible to true by using the parent component

   //setting parcial_result to true on the parent doesn't affect the visible variable anymore.  

    }
  }

  ngOnInit() {

  }

似乎我无法重新分配input属性。我该如何补救。

2 个答案:

答案 0 :(得分:0)

原因是父组件的parcial_result已设置为true,因此您无法将其重新分配给true来查看更改。为了使此工作有效,您需要将更改传达给父组件。为此使用输出。我会举个例子。

父项

parcial_result:boolean = false;

fetchData(): void {
  this.parcial_result = true;
}
....
<app-window [visible]="parcial_result"
            (hide)="parcial_result = false"></app-window>

您的子组件

@Input() visible: boolean = true;
@Output() hide = new EventEmitter();

constructor(private eRef: ElementRef) { }

  @HostListener('document:click', ['$event'])
    //if the user clicks outside this component I hide it again.

  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {

    } else {
      // instead of setting the prop, we just inform the parent
      hide.emit();
    }
  }

答案 1 :(得分:0)

您的子组件应发出对“可见”的更改。为此,您可以create a two-way binding

子组件:

export class ChildComponent {
    @Input() visible: boolean = false;
    @Output() visibleChange = new EventEmitter<boolean>();

    fetchData(): void {
       this.visible= true;
       this.visibleChange.emit(this.parcial_result);
    }
}

父模板:

<app-window [(visible)]="parcial_result"></app-window>