【问题标题】:Change directive attribute from child component in Angular 2从Angular 2中的子组件更改指令属性
【发布时间】:2016-07-27 19:21:26
【问题描述】:

我有一个带有以下指令<child-component [hidden]="!visible"></child-component> 的父组件。最初,与该指令关联的子组件是隐藏的,在某些事件之后,我想让它可见,所以我使用父组件中的按钮 <button (click)="showMe()">Show child</button> 来更改此属性。

export class App {
  constructor() {
    this.visible = false;
  }

  showMe() {
    this.visible = true;
  }
}

问题是,一旦这显示了子组件,我需要在子组件中提供一个按钮<button (click)="hideMe()">Hide</button> 来再次隐藏它:

export class ChildComponent {
  constructor(private _element: ElementRef, private _renderer: Renderer) {}

  hideMe() {
    let el = this._element.nativeElement);
    this._renderer.setElementStyle(el, 'visibility', 'hidden');
  }
}

我不确定这部分,但至少它有效。现在,如果我想再次更改 child-component 指令的属性 hidden 会发生什么?调用 showMe() 不起作用,大概是因为应用样式中的某种优先级。

这样做的正确方法是什么?

Demo: 首先点击“显示孩子”,然后点击“隐藏”,然后再次尝试点击“显示孩子”。最后点击的按钮不起作用。

谢谢

【问题讨论】:

    标签: attributes angular


    【解决方案1】:

    不确定这是您想要的方法,但我认为它的行为与描述的一样:

    @Component({
      selector: 'child-component',
      providers: [],
      host: {'[hidden]': 'hidden'},
      template: `
        <div>
          This is the child
        </div>
        <button (click)="hidden=true">Hide</button>
      `,
    })
    export class ChildComponent {
      @Input() hidden:boolean = false;
    }
    
      <child-component #child [hidden]="true"></child-component>
      <button (click)="child.hidden=false">Show child</button>
    

    Plunker example

    您的示例中的问题是 hidden 属性和 visibility: hidden 得到冲突的值。

    【讨论】:

    • 谢谢。阅读文档后,我想我了解您在做什么。唯一的问题是我不能在不破坏其他东西的情况下将子组件启动为隐藏。在这种情况下你有解决方案吗?
    • 我更新了我的答案。只需添加 [hidden]="true" 即可使其最初隐藏。
    • 当然 :-) 谢谢。顺便问一下,这是完成子组件和父组件之间通信的最直接的方式吗?
    • 而不是引用模板变量#child,您可以引用父字段中的字段(例如您的示例中的visible)。这是更常见的方式,但在此示例中,仅在模板中使用直接引用似乎更直接。
    • 是的 inputs: ["hidden"] ... input:boolean = false; 与 @Input() input:boolean = false; 相同,只是表达方式不同。您需要输入才能传递像&lt;child-component [hidden]="false">` 这样的值。我们可以为输入使用不同的名称,但我没有看到发明新名称的理由。
    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 2023-04-06
    • 2016-12-20
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多