Angular8 Material中如何为按钮文本绑定数据?附代码求助
Hey there! Let's walk through how to get your button text data binding working smoothly in Angular 8 Material. Here are some key checks and optimizations for your code:
1. Safely Handle Asynchronous Data
Your getSummaryAll() method runs asynchronously, which means when your component first loads, summary will be undefined until the API call finishes. This can cause a "Cannot read property 'tools' of undefined" error. Fix this with the safe navigation operator (?.) to guard against undefined values:
<button mat-flat-button class="rectangle"> <div class="external">{{ summary?.tools }} </div> </button>
2. Use Async Pipe (Recommended Best Practice)
Instead of manually subscribing in ngOnInit, leverage Angular's async pipe. It automatically manages subscriptions (preventing memory leaks) and handles the async data flow for you:
Update TypeScript code:
summary$: Observable<any>; // Declare an observable property ngOnInit() { this.summary$ = this.summaryService.getSummaryAll().pipe(take(1)); }
Update HTML code:
<button mat-flat-button class="rectangle"> <div class="external">{{ (summary$ | async)?.tools }} </div> </button>
3. Verify Your Data Structure
Double-check that the data returned from getSummaryAll() actually includes a tools property. Add a console log to confirm the structure:
ngOnInit() { this.summaryService.getSummaryAll() .pipe(take(1)) .subscribe(data => { console.log('Fetched summary data:', data); // Inspect the data here this.summary = data; }); }
4. Optional: Add Loading Placeholder
If you want to show placeholder text while waiting for the data to load, use the nullish coalescing operator (??):
<button mat-flat-button class="rectangle"> <div class="external">{{ summary?.tools ?? 'Loading...' }} </div> </button>
内容的提问来源于stack exchange,提问作者rezion

