简体   繁体   English

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

[英]Change directive attribute from child component in Angular 2

I have a parent component with the following directive <child-component [hidden]="!visible"></child-component> . 我有一个带有以下指令<child-component [hidden]="!visible"></child-component> parent <child-component [hidden]="!visible"></child-component>的父组件。 Initially, the child component associated to this directive is hidden and after some event, I want to make it visible, so I'm using a button <button (click)="showMe()">Show child</button> in the parent component to change this property. 最初,与此指令关联的子组件是隐藏的,在某些事件之后,我想使其可见,因此我在按钮中使用了<button (click)="showMe()">Show child</button> 。父组件来更改此属性。

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

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

The problem is that, once this shows the child component, I need to provide a button <button (click)="hideMe()">Hide</button> in the child component to hide it again: 问题是,一旦显示了子组件,我就需要在子组件中提供按钮<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');
  }
}

I'm not sure about this part but at least it works. 我不确定这部分内容,但至少可以使用。 Now, what happens if I want to change the property hidden of the child-component directive again? 现在,如果我想再次更改child-component指令的hidden属性会怎样? Calling showMe() doesn't work, presumably because of some kind of precedence in the applied styles. 调用showMe()不起作用,可能是由于所应用样式中的某种优先级。

What is the correct way to do this? 正确的方法是什么?

Demo : First click on 'Show child', then click on 'Hide' and then try to click on 'Show child' again. 演示 :首先单击“显示孩子”,然后单击“隐藏”,然后再次尝试单击“显示孩子”。 The last button clicked doesn't work. 最后单击的按钮不起作用。

Thanks 谢谢

Not sure this is the approach that you want, but I think it behaves like described: 不确定这是否是您想要的方法,但是我认为它的行为类似于所描述的:

@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 柱塞示例

The problem in your example is that the hidden property and visibility: hidden get conflicting values. 您的示例中的问题是hidden属性和visibility: hidden获得冲突的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM