Home > Blockchain >  How to add content to template dynamically in Angular?
How to add content to template dynamically in Angular?

Time:03-20

I am using socket.io in my project. When a user post a request to server, an emit event will be sent (broadcasted) from the server to all connected sockets. The emit will send all the new requests available in the database to the client (to be displayed to the user).

I am looping through a static variable (StaffScreenComponenet.allRequests) inside staff-screen.component.html:

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

I have another method (below code) that prints the value received from the server to the console but the content in the html is not reflecting the actual content in StaffScreenComponent.allRequests. In other words, I can see that StaffScreenComponent.allRequests length increased but the new values in StaffScreenComponent.allRequests are not displayed in HTML.

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

The component ts file code is below:

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

}

And the service file `` code below:

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

And the component that include the section of the code that changes the StaffScreenComponent.allRequests is below:

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

How can I render the content in the html again after it is being created?

CodePudding user response:

Are you using OnPush ChangeDetection? If yes, you have to inject changedetectorref and run markforcheck once the value are updated.

  • Related