如何在Angular中动态添加内容到模板?

How to add content to template dynamically in Angular?

我在我的项目中使用 socket.io。当用户 post 向服务器发出请求时,一个 emit 事件将从服务器发送(广播)到所有连接的套接字。 emit 会将数据库中可用的所有新请求发送到客户端(以显示给用户)。

我在 staff-screen.component.html:

中循环一个静态变量 (StaffScreenComponenet.allRequests)
   <mat-grid-list cols="4">
        <div *ngFor="let request of retrieveRequests()">
        <mat-grid-tile>
            <app-list-requests tableName="{{request.tableName}}" requestType="{{request.requestType}}" date="{{request.createdAt}}"></app-list-requests>
        </mat-grid-tile>
        </div>

   </mat-grid-list>

我有另一种方法(代码下方)将从服务器接收到的值打印到控制台,但 html 中的内容并未反映 StaffScreenComponent.allRequests 中的实际内容。换句话说,我可以看到 StaffScreenComponent.allRequests 长度增加了,但是 StaffScreenComponent.allRequests 中的新值没有显示在 HTML.

  retrieveRequests(){
    console.log(StaffScreenComponent.allRequests)
    return StaffScreenComponent.allRequests;
  }

组件ts文件代码如下:

export class StaffScreenComponent implements OnInit, OnChanges {
  longText = `The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog
  from Japan. A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was
  originally bred for hunting.`;

  constructor(private httpService: HttpClient, private webSocketService: WebSocketService, private socket: Socket) {}
  ngOnChanges(changes: SimpleChanges): void {
    console.log('test');
    changes['allRequests'].firstChange;
    console.log(changes['allRequests'].currentValue)
  }

  public static allRequests: any;
  @Input()
  check: any;
  
  ngOnInit(): void {
    this.httpService.get('http://localhost:3000/api/getRequests').subscribe(res=>{
      console.log(res)
      StaffScreenComponent.allRequests = res;

     
    });
    this.socket.on('fetchRequests', (data: string) => {
      console.log('checking')
        console.log(data);
      });
  }

  retrieveRequests(){
    console.log(StaffScreenComponent.allRequests)
    return StaffScreenComponent.allRequests;
  }

}

服务文件``代码如下:

export class WebSocketService {
  constructor(private socket: Socket) { }

  // emit event
    fetchRequests(requestMdel: AddRequestModel) {
        this.socket.emit('fetchRequests', requestMdel);
    } 

    // listen event
    OnFetchRequests() {
        return this.socket.fromEvent('fetchRequests');
    }

    setupSocketConnection(){
        this.socket.on('fetchRequests', (data: string) => {
            console.log(data);
            localStorage.setItem('allRequests', JSON.stringify(data[0]));
            StaffScreenComponent.allRequests = data;
          });
    }
}

包含更改 StaffScreenComponent.allRequests 代码部分的组件如下:

export class ItemDisplayComponent implements OnInit {
  allRequests: any;

  @Input()
  name: string = '';

  @Input()
  _id: string = '';

  requestTypes = {
    waiter: "waiter",
    bill: "bill"
  }

  constructor(private itemsAPIService: ItemsApiService, private webSocketService: WebSocketService) { }

  ngOnInit(): void {
    this.webSocketService.setupSocketConnection();
  }

  onRequest(requestType: string, tableName: string){
    // console.log(requestType + ' / ' + tableName);
    let requestModel = new AddRequestModel(tableName, requestType);
    this.itemsAPIService.submitRequest(requestModel);

    this.webSocketService.fetchRequests(requestModel);
    // this.webSocketService.setupSocketConnection();
    console.log(StaffScreenComponent.allRequests);
  }
}

html中的内容创建后如何再次渲染?

您在使用 OnPush ChangeDetection 吗?如果是,您必须在值更新后注入 changedetectorref 和 运行 markforcheck。