首页 文章

从Angular 2中的子组件更改指令属性

提问于
浏览
1

我有一个父组件,其中包含以下指令 <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:首先单击'Show child',然后单击'Hide',然后再次尝试单击'Show child' . 单击最后一个按钮不起作用 .

谢谢

1 回答

  • 2

    不确定这是你想要的方法,但我认为它的行为如下所述:

    @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 得到冲突的值 .

相关问题