在Angular 6中单击每个单选按钮时,如何向body元素添加相应的类
我想在单击每个单选按钮时,将特定类添加到body标记,将活动类添加到父元素 例如:在Angular 6中单击每个单选按钮时,如何向body元素添加相应的类,angular,typescript,radio-button,angularjs-ng-click,ng-class,Angular,Typescript,Radio Button,Angularjs Ng Click,Ng Class,我想在单击每个单选按钮时,将特定类添加到body标记,将活动类添加到父元素 例如: 布局1 布局2 布局3 当我单击值为“layout1”的单选按钮时,应将类别“a”添加到body标签中,当我单击每个单选按钮时,它应相应地更改为类别“b”和“c”。从angular导入文档 import { Component, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Component({ s
布局1
布局2
布局3
当我单击值为“layout1”的单选按钮时,应将类别“a”添加到body标签中,当我单击每个单选按钮时,它应相应地更改为类别“b”和“c”。从angular导入文档
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
layout1;
layout;
layout3;
constructor(@Inject(DOCUMENT) private document: any) { }
addClass($event) {
if (this.document.body.classList) {
let className = Object['values'](this.document.body.classList).filter(d => d !== $event);
className.map(d => this.document.body.classList.remove(d));
this.document.body.classList.add($event);
}
else {
this.document.body.classList.add($event);
}
}
}
component.html
<form #f="ngForm">
<input type="radio" value="a" (ngModelChange)="addClass($event)"[ngModel]="layout1" name="1" ngModel>Layout 1<br>
<input type="radio" value="b"(ngModelChange)="addClass($event)" [ngModel]="Layout2" name="1" ngModel>Layout 2<br>
<input type="radio" value="c" (ngModelChange)="addClass($event)" [ngModel]="layout3" name="1" ngModel>Layout 3
</form>
布局1
布局2
布局3
示例:是否有办法将多个类添加到正文中?。如果我单击一些单选按钮,我想将多个类添加到body标记中。是的,您可以使用这个.document.body.classList.add($event);它将像一个b cI试图使用此代码段在同一组件内更改我的导航栏颜色一样附加该类,但不起作用!!。类“.navbar primary”和“.navbar success”等应以相同的方式添加到navbar。是否尝试更改颜色?是。我尝试了同样的代码,将选择器主体更改为navbar。
<form #f="ngForm">
<input type="radio" value="a" (ngModelChange)="addClass($event)"[ngModel]="layout1" name="1" ngModel>Layout 1<br>
<input type="radio" value="b"(ngModelChange)="addClass($event)" [ngModel]="Layout2" name="1" ngModel>Layout 2<br>
<input type="radio" value="c" (ngModelChange)="addClass($event)" [ngModel]="layout3" name="1" ngModel>Layout 3
</form>