Reputation: 758
I have 2 components- A,B And want from A change B's class.for example change ng-valid to ng-invalid
<A #a></A >
<B> </B>
From B I want give class to A,or change A's ng-valid class to ng-invalid.
Upvotes: 1
Views: 2723
Reputation: 16917
See this plunker to get an idea of how to do it: https://plnkr.co/edit/wz771Lnnn3GjHWFmykGl?p=preview
As you commented, you could use an @Input
to get access to that component..
import {Component, NgModule, Input, ElementRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'AComp',
template: 'a-component',
styles: [
':host(.ng-valid) { color: green; font-weight: bold; }',
':host(.ng-invalid) { color: red; font-weight: bold; }'
]
})
export class AComp {
constructor(private _eRef: ElementRef) {}
public addClass(c: string) {
console.dir(this._eRef);
this._eRef.nativeElement.classList.add(c);
}
public removeClass(c: string) {
this._eRef.nativeElement.classList.remove(c);
}
}
@Component({
selector: 'BComp',
template: 'b-component'
})
export class BComp {
@Input('a-comp') private _aComp: AComp;
constructor() { }
ngOnInit() {
this._aComp.addClass('ng-valid')
setTimeout(() => this._aComp.addClass('ng-invalid'), 1000);
setTimeout(() => this._aComp.removeClass('ng-invalid'), 3000);
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<AComp #acmp></AComp>
<br />
<BComp [a-comp]="acmp"></BComp>
</div>
`,
})
export class App {
constructor() {
this.name = 'Angular2'
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, AComp, BComp ],
bootstrap: [ App ]
})
export class AppModule {}
Upvotes: 2