[英]Angular 2- change class from one component to another
I have 2 components- A,B And want from A change B's class.for example change ng-valid to ng-invalid 我有2个组件-A,B并希望从A更改B的类。例如将ng-valid更改为ng-invalid
<A #a></A > <B> </B>
From BI want give class to A,or change A's ng-valid class to ng-invalid. 从BI希望将类赋予A,或将A的ng-valid类更改为ng-invalid。
See this plunker to get an idea of how to do it: https://plnkr.co/edit/wz771Lnnn3GjHWFmykGl?p=preview 看到这个笨拙的人以了解如何做到这一点: https ://plnkr.co/edit/wz771Lnnn3GjHWFmykGl?p=preview
As you commented, you could use an @Input
to get access to that component.. 正如您所评论的,您可以使用
@Input
来访问该组件。
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 {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.