Angular 9-如何从DOM中选择元素(即表单控件)并向其添加CSS类



我正在.html文件中动态生成表单控件。

<div *ngFor="let question of questions" style="  width: 40%;">
<app-question [question]="question" [formGroup]="ratingForm"></app-question>
</div>

然而,我需要能够动态地将css类添加到html文件中自动生成的两个表单控件中。我想我需要使用@ViewChild在表单控件自动生成后找到它,然后修改它以有条件地添加我想要的CSS类。我只想在两个表单控件的值之一发生更改的情况下添加css类。

所以我有两个表单控件。屋顶名称和屋顶年份。如果"Roof Name"或"Roof Year"值发生更改,请在这两个值中都添加一个Css Class.高亮显示。如何将其添加到打字脚本中?我有一个OnControlChange方法,它在每次更改字段时都会触发。

questions: any[];
ngOnInit() {
let formControl = new RatingFormElements();
this.formNames = Object.getOwnPropertyNames(formControl);
let tempQuestions: any[] = 
this.questionService.getQuestionsByKeys(this.formNames);
this.questions = tempQuestions; //this becomes a formGroup
}
private onControlChange(value: any, name: string) {
if (name == "roofyear" || name == "roofname") {
//I need to do something here
//something like this:
this.questions.controls["roofname"].cssClass = "highlight"
//or something like this:
//Select DOM Element by ID: roofyear
//add CssClass highlight to it
}
}
}

这是自动生成的html。

<input _ngcontent-egw-c322="" matinput="" oninput="this.value = this.value.toUpperCase()" uppercasepipe="" class="mat-input-element mat-form-field-autofill-control ng-tns-c78-77 cdk-text-field-autofill-monitored ng-dirty ng-touched ng-valid" ng-reflect-placeholder="Roof Year" ng-reflect-name="roofyear" autocomplete="on" ng-reflect-mask-expression="0000" ng-reflect-thousand-separator="" ng-reflect-suffix="" ng-reflect-prefix="" ng-reflect-id="roofyear" type="text" ng-reflect-type="text" id="roofyear" placeholder="Roof Year" aria-invalid="false" aria-required="false">

它具有id="0";屋顶年";所以我的代码所需要做的就是能够通过ID找到这个DOM元素,然后向它添加一个css类

根据未包含的实际标记,您可以使用类似的[class.x]=condition来完成此操作

<input [class.highlight]="name=='roofyear' || name=='roofname'"/>

您可以通过以下方式创建FormControl及其功能:

@Component({
selector: 'app-my',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {
public fg: FormGroup;
public input: FromControl = new FormControl('', Validators.required);
public constructor() { }
public ngOnInit(): void {    
this.fg = new FormGroup({
input: this.input          
});
}
}

我想,为了能够根据您的值更改类,您可以在您的html:中这样做

<div [ngClass]="{'my-class': input.value === 'example'}"></div>

有关如何使用ngClass指令的更多示例,请参阅此链接:StackOverflow-Angular:带*ngClass 的条件类

编辑

@Component({
selector: 'app',
template: `
<div #myDiv>Some text</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.innerHTML);
}
}

最新更新