简体   繁体   中英

Angular component not refreshing when variable is changed

I hope this is not a duplicated question... I've been looking for a solution for the whole night.
I'm writing a project for the university and they want me to write kind of a data monitor, that displays data from another application.
We have to use rust, so I thought I could use Tauri to make the UI job easier.
The problem I'm facing is the following: From angular I register the callback to the add_data event with the listen method. From there I update an attribute with the value received from the event.
The frontend is only displaying that element, but when it is updated, nothing happens to the frontend Here is my code:

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

    title = 'trader-visualizer-tauri-2';

    out: string = "out";

    ngOnInit(): void {
        listen('add_data', (event: TauriEvent<number>) => {
            console.log("add_data event received");
            this.out = event.payload.toString();
        })
    }
}
<main>
    {{out}}
</main>

这是我看到的

Is there a way to force re-render the component?

I'm guessing listen is a function from a JS library you're using. When using such functions and updating your properties from inside their callbacks, Angular does not know that the values have changed and that's why you need to notify Angular to detect the changes.

It is pretty easy to do. Inject ChangeDetectorRef in your constructor and at the bottom of listen , call its cdRef's detectChanges method.

// Inject ChangeDetectorRef
constructor(private cdRef: ChangeDetectorRef) {}

...

ngOnInit() {
  listen('add_data', (event: TauriEvent<number>) => {
    console.log("add_data event received");
    this.out = event.payload.toString();

    // And add the following
    this.cdRef.detectChanges();
  })
}

To learn more about Angular Change Detection, here's a resource: https://indepth.dev/posts/1058/a-gentle-introduction-into-change-detection-in-angular

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