Consider a scenario where you have a component with logic to toggle the visibility of its contents:
@Component({
selector: 'hello',
template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`,
styles: [`h1 { font-family: Lato; } div { border: 1px solid blue }`]
})
export class HelloComponent {
@Input() name: string;
visible: boolean;
ngOnInit() {
this.visible = this.name === "Stranger"
}
}
Now, using this component in another component like so:
<div class="container">
<hello class='hello-class' name="Stranger"></hello>
<!-- This will not be visible -->
<hello class='hello-class' name="Not stranger"></hello>
</div>
The second use of the hello
component remains invisible due to the conditions set inside the component. However, the styles applied to hello-class
are still affecting the component even when it's hidden.
You cannot move the logic to directly show/hide the component to the parent element. Therefore, adding an *ngIf
before the component is not an option.
Is there a way to apply these styles only if the component is visible?
Check out this stackblitz link for a demonstration of the issue: https://stackblitz.com/edit/angular-ivy-mfrb7j