有角材料。超时中的值更改不会应用

问题描述 投票:0回答:1

这可能归结为我对 Angular 的普遍误解,因为我目前只是在玩它。我正在尝试使用“角度/材质/进度条”组件显示假进度条。 (https://material.angular.io/components/progress-bar/

我可以在“app.component.html”中像这样显示进度条:

<mat-progress-bar id="progBar1" mode="determinate" [value]= "progressBarValue" class="visible"></mat-progress-bar>

我还可以使用“app.component.ts”中的“value”输入来设置其进度一次。但是,如果我使用 setTimeout() 或 setInterval() 来延迟更改或重复添加它不会应用的值:

import { Component } from '@angular/core';
import {MatProgressBar, MatProgressBarModule} from '@angular/material/progress-bar'; 

var progressBarValueInternal:number = 1;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'Eduardeo-App';
  progressBarValue = progressBarValueInternal;
}

progressBarValueInternal=50;
setTimeout(()=>{console.log("Setting ProgressBar to 75"); progressBarValueInternal=75;}, 5000);

使用上面的代码,控制台将打印“Setting ProgressBar to 75”,但进度条将保持在最初设置的 50%。有什么想法,为什么会出现这种情况?

javascript html angular typescript
1个回答
0
投票

所有初始化操作都需要在 ngOnInit 钩子上进行

Angular 组件生命周期文档

import { Component } from '@angular/core';
import {MatProgressBar, MatProgressBarModule} from '@angular/material/progress-bar'; 

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'Eduardeo-App';
  progressBarValue = 1;
  progressBarValueInternal=50;

  ngOnInit(){
      setTimeout(()=>{
          console.log("Setting ProgressBar to 75"); this.progressBarValueInternal=75;
      }, 5000);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.