r_31415
r_31415

Reputation: 8982

Change directive attribute from child component in Angular 2

I have a parent component with the following directive <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.

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:

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? Calling showMe() doesn't work, presumably because of some kind of precedence in the applied styles.

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

Upvotes: 1

Views: 2135

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657781

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.

Upvotes: 3

Related Questions