1

У меня есть кнопка с текстом, который генирируется каждые 3 секунды. Мне нужно сделать так, чтоб при появлении в тексте ноля, тексту добавлялся новый класс. У меня уже есть проверка на содержание ноля в строке. Как добавить класс элементу, в котором этот текст? Typescript code:

export class TextFieldComponent implements OnInit {
  randomString:string = '';
  
  constructor() {
    this.getString();
  }

  ngOnInit(): void {
    const source = interval(3000);
    source.subscribe(() => this.getString())
  }

 getString(){
    this.randomString = '';
    while (this.randomString.length < 5) {
      this.randomString = btoa(Math.random().toString()).substr(10, 5);
    }
   this.whatStringCreated(this.randomString)
    return this.randomString;
  }

  whatStringCreated(randomString:string){
    if(this.randomString.includes('0')){
      this.containZero();
    }
}
containZero(): void{
   //???
    console.log("0");
  }

Html code:

<div [className]="'d-grid gap-2 m-5'">
  <button type="button" id="textField" [className]="'btn btn-primary fs-1'" (click)="getString()" style="height: 100px; letter-spacing: 0.5em">{{randomString}}</button>
</div>

1
  • возможно стоит посмотреть на ngClass 26 июл 2021 в 5:22

1 ответ 1

1

Во-первых, использовать [className]="'d-grid gap-2 m-5'" в данном контексте не имеет смысла, так как имя класса не меняется и не генерируется, можно использовать обычный атрибут class.

Во-вторых, для того, чтобы проверить есть ли подстрока в строке, можно использовать метод .includes().

export class AppComponent implements OnInit {
  randomString: string = '';

  ngOnInit(): void {
    setInterval(() => this.getString(), 3000);
  }

  getString() {
    this.randomString = '';
    while (this.randomString.length < 5) {
      this.randomString = btoa(Math.random().toString()).substr(10, 5);
    }
    return this.randomString;
  }

  get containZero(): boolean {
    return this.randomString.includes('0');
  }
}
.has-zero {
  background-color: red;
}
<button [ngClass]="{'has-zero': containZero}" (click)="getString()">{{randomString}}</button>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.