首页 > 解决方案 > 如何使用 Angular 6 中的绑定更改 html 视图

问题描述

我有一个 Angular 6 项目,我有一个像这样的书的组件

<div class="col-md-4 agileinfo_single_left">
    <img id="BigBookView" src="public/books/images/{{book.photo}}" alt=" " class="img-responsive">
</div>
<div class="col-md-8 agileinfo_single_right">
  <h1>{{book.name | uppercase}}</h1>
  <h2>Series: {{book.seriesName}}</h2>
  <h3>Author: {{book.author}}</h3>
  <h4></h4>
  <div class="w3agile_description">
    <h4>Summary : {{book.summary}}</h4>
  </div>
  <div class="snipcart-item block">
    <div class="snipcart-thumb agileinfo_single_right_snipcart">
       <h4 class="m-sing">Price: {{book.price}}$</h4>
       <h4 class="m-sing">Seller: {{book.seller}}</h4>
    </div>
    <div class="snipcart-details agileinfo_single_right_details">
      <form action="#" method="post">
        <fieldset>
          <input type="submit" name="submit" value="Add to cart" class="button">
        </fieldset>
      </form>
    </div>
  </div>

所有这些都在模态中,每次我选择一本书并打开模态并假设在此 html 中显示书籍数据时。这是组件类型脚本

export class BigBookViewComponent implements OnInit {
  @Input()
  public book:Book = new Book();
  constructor() { }

  ngOnInit() {
  }

  public changeBook(newBook: Book) {
    console.log(this.book);
    this.book = newBook;
  }

}

使用该功能changeBook,我向该组件发送了一本要显示的新书,但 html 和 UI 没有改变,即使我可以在该console.log(this.book);行中看到该书确实正在发送。如何更改 html 以显示不同的书?

标签: bindingangular6angular-components

解决方案


您应该在 ngOnInit 方法上分配这本书。在构造函数中分配时,组件的单个实例将保留原书。


推荐阅读