angular - 在子 Angular2 中访问父级的变量

标签 angular

我的父组件中有一个变量,我想在我的子组件中进行编辑。 我尝试了 @Input 但似乎不起作用!我怎样才能实现将var传递给 child 并监听变化?

父级:

export class Parent implements OnInit {
    showModal : boolean = false;
}

child :

export class Child implements OnInit {
    @Input() showModal: boolean;

    // calling this function on (click) button.
    closeModal() {
      this.showModal = false;
    }
}

谢谢。

最佳答案

export class Child implements OnInit {
    @Input() showModal: boolean;
    @Output() showModalChange:EventEmitter<boolean> = new EventEmitter<boolean>();

    // calling this function on (click) button.
    closeModal() {
      this.showModal = false;
      this.showModalChange.emit(this.showModal);
    }
}

父元素html

<child [(showModal)]="showModal"

应该做你想做的事。

关于angular - 在子 Angular2 中访问父级的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41910506/

相关文章:

javascript - Angular2 ngIf 在 false 时创建空元素

css - 通过 Angular 获取应用于元素的类属性

使用 Bootstrap 的 Angular 6 库

angular - 类型 'Observable<string[]>' 缺少类型 'string[]' 的以下属性 : length, pop、push、concat 和另外 25 个

Angular 2+ 无法读取未定义的属性 'id'

angular -::ng-deep 将被弃用 - 还有其他选择吗?

Angular 9 Ivy - 通用类型 'ɵɵFactoryDef' 需要 2 个类型参数

javascript - lodash过滤器返回无法读取null的属性 'indexOf'

angular - 为什么 Angular 中的 ngOnInit 不是私有(private)的?

javascript - Angular 2 ES6/7 Eventemitter 更新其他组件