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

标签 angular typescript

父组件类

export class Parent {
   show: boolean = false;
   constructor() { }
   showChild() {
      this.show = true;
   }
}

父组件模板

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

子组件类

export class Child {
   @Input isShow: boolean = false;
   constructor() { }
   onClick() {
      this.isShow = false;
    }
}

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

为什么?

最佳答案

因为您使用的是方括号,所以该值仅从父级传递给子级。

为了让值双向传递,您需要使用双向数据绑定(bind)。

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

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

模板应该是

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

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

看一下双向数据绑定(bind)教程页面:

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

关于angular2 在子组件中更改@input 值然后在父组件中更改此值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43373122/

相关文章:

javascript - 如何从 Chrome REPL 调试 React 变量

javascript - 当我在解构原始类型后解构 Partial 类型时,Typescript 不会给出错误

css - 当其容器/父元素悬停时将 css 样式应用于元素 Angular

angular - Angular 的组件名称相同

node.js - 使用 Blazor 在 NodeJS 应用程序中使用 .NET 类库

angular - 如何将数组数据作为formdata angular 4发送

javascript - 将变量插入数组中的辅助子对象

javascript - 动态创建路线

angular - PrimeNG 表在值更改后保存所选页面

angular - viewchildren 的 offsettop 和 offsetleft