View is not updating when I modify the books variable inside the subscribe block of Material...

Discussão em 'Angular' iniciado por Masudalimran, Setembro 24, 2024.

  1. Masudalimran

    Masudalimran Guest

    In the books.component.ts file

    export class BooksComponent{
    // books variable
    books: IBook[] = [];

    // constructor to initialize BookService
    constructor(private bookService: BookService) {}

    // Handle Dialog
    readonly dialog = inject(MatDialog);

    openDialog() {
    const dialogRef = this.dialog.open(BookAddDialogComponent, {
    data: { booksCount: this.books.length },
    });

    dialogRef.afterClosed().subscribe((result) => {
    if (result) {
    const newBook = dialogRef.componentInstance.newBook;
    console.log(newBook); // { id: 0. title: 'Harry Potter', author: 'J.K. Rowling'}
    this.books = this.bookService.addBook(this.books, newBook);
    console.log(this.books); // [{ id: 0. title: 'Harry Potter', author: 'J.K. Rowling'}]
    }
    });
    }

    }


    In the books.component.html file

    <h4>Book List ({{ books.length }})</h4>
    <ul>
    <li *ngFor="let book of books">
    {{ book.id }} - {{ book.title }} - {{ book.author }}
    </li>
    </ul>


    I have checked the console. It shows proper values for both newBook & this.books. But it does not show in the html file.

    I tried setting the this.books variable in localStorage & then getting it back so that this.books sustains with reload. It worked then, when I refreshed the page it has successfully added the new book and showed in view. But Without reload it did not update in the view.

    I also tried modifying a dummy variable a inside the subscribe block

    export class BooksComponent{
    a: number = 0;

    // Handle Dialog
    readonly dialog = inject(MatDialog);

    openDialog() {
    const dialogRef = this.dialog.open(BookAddDialogComponent);

    dialogRef.afterClosed().subscribe((result) => {
    if (result) {
    this.a = 1;
    console.log(a) // 1
    }
    });
    }

    }


    In the books.component.html file

    <h4> {{ a }} </h4> // 0


    It still did not update in the view. a still showed 0 in view. console.log(a) shows 1 but in view it is unchanged.

    This issue is only happening inside the subscribe block. If I make any changes to the variable outside the block like this

    export class BooksComponent{
    a: number = 0;

    // Handle Dialog
    readonly dialog = inject(MatDialog);

    openDialog() {
    const dialogRef = this.dialog.open(BookAddDialogComponent);

    dialogRef.afterClosed().subscribe((result) => {
    if (result) {

    }
    });

    this.a = 1;
    console.log(a) // 1
    }

    }


    In the books.component.html file

    <h4> {{ a }} </h4> // 1


    Then it works fine and shows proper value in view.

    Please help me figure out the issue.

    Continue reading...

Compartilhe esta Página