简体   繁体   中英

Angular 9 - How to select element (that is a formcontrol) from the DOM and add a CSS Class to it

I am dynamically generating formcontrols in the.html file.

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

However, I need to dynamically be able to add css classes to two of the formcontrols that are auto-generated in the html file. I think I need to use @ViewChild to find the formcontrol after it's been auto-generated and then modify it to add the CSS Class I want conditionally. I only want to add the css classes if one of the two formcontrol's value have been changed.

So I have two form controls. Roof Name and Roof Year. If Roof Name OR Roof Year value changes, add a Css Class.highlight to both of them. How do I add this in the typescript? I have an OnControlChange method that triggers every time a field has been changed.

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
    }
  }
}

This is the html that gets auto-generated.

<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">

it has id="roofyear" so all my code needs to do is be able to find this DOM element by ID and then add a css class to it.

Depends on your actual markup which is not included, you will be able to do this using [class.x]=condition like

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

You can get access to your FormControl and it's function by creating it like this:

@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          
    });
  }
}

To be able to change the class depending on your value I assume, you can do this in your html:

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

For more example on how to use the ngClass directive see this link: StackOverflow - Angular: conditional class with *ngClass

EDIT

@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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM