Home > Mobile >  How to change a host value from a different host?
How to change a host value from a different host?

Time:10-12

I need to extend an existing component to allow it to remove a margin from the top.

This margin is set within the :host pseudoelement

:host {
  margin-top: auto;
}

I'd like to do add a new class that overwrites this configuration, something like this.

:host(.remove-margin-top) {
  :host {
    margin-top: 0;
  }
}

But when i use the class remove-margin-top, the changes are not being implemented. Any ideas on how can i work around this?

CodePudding user response:

To allow ParentComponent to change the style of a ChildComponent's host, we can use @HostBinding and @Input together.

  • @HostBindng allow us to bind a class to the ChildComponent.

  • @Input allow us to the supply a boolean value to turn on/off the class.

To avoid affecting the rest of the consumers, we will set a default value for the hasMarginTop to true. This way, the existing consumers doesn't need to update their code. The new one can use hasMarginTop and set it to true if it doesn't need to have the margin-top.

child.component.ts

@Component({
  ...
})
export class ChildComponent {

  @HostBinding('class.has-margin-top')
  @Input()
  public hasMarginTop = true; 

}

child.component.css

:host {
  display: block;
}

// this only apply when hasMarginTop is true.
:host.has-margin-top {
  margin-top: 200px;
}

parent.component.html

...
<!-- remove margin -->
<app-child hasMarginTop="false"></app-child>


<!-- default has margin -->
<app-child></app-child>
...
  • Related