angular2更改子组件中的@input值然后更改父组件中的此值不起作用

前端之家收集整理的这篇文章主要介绍了angular2更改子组件中的@input值然后更改父组件中的此值不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
父组件类
  1. export class Parent {
  2. show: boolean = false;
  3. constructor() { }
  4. showChild() {
  5. this.show = true;
  6. }
  7. }

父组件模板

  1. <child [isShow]="show"></child>

子组件类

  1. export class Child {
  2. @Input isShow: boolean = false;
  3. constructor() { }
  4. onClick() {
  5. this.isShow = false;
  6. }
  7. }

在我触发子组件中的onClick()后,showChild()无法显示子组件.

为什么?

由于您使用的是方括号,因此该值仅从父级传递给子级.

为了使值双向,您需要使用双向数据绑定.

这意味着你的isShow属性应该是这样的:

  1. @Input() isShow: boolean;
  2. @Output() isShowChange = new EventEmitter<boolean>();

模板应该是

  1. <child [(isShow)]="show"></child>

要么

  1. <child [isShow]="show" (isShowChange)="show = $event"></child>

看一下双向数据绑定教程页面

https://angular.io/guide/template-syntax#two-way-binding—

猜你在找的Angularjs相关文章