Component Host 屬性設定

在 Angular 中,可以在 @Component 的設定中使用 host 來為元件設定預設屬性。不論這個元件在哪裡被使用,都會帶有這個屬性。

使用場景

假設有以下 CSS:

.control label {
  display: block;
  font-size: 0.8rem;
  font-weight: bold;
  margin-bottom: 0.15rem;
  color: #4f4b53;
}

.control input,
.control textarea {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  font: inherit;
  font-size: 0.9rem;
  color: #4f4b53;
}

元件的 HTML:

<label>{{ label }}</label>
<ng-content select="input, textarea" />

問題

如果不使用 host,要讓元件具有 control 類別有兩種方式:

  1. 在模板中加入額外的 div:

<app-control>
  <div class="control">
    <label>{{ label }}</label>
    <input .../>
  </div>
</app-control>

這會產生多餘的 DOM 層級。

  1. 每次使用元件時都加上 class:

<app-control class="control" label="Title">
  <input name="title" id="title" />
</app-control>
<app-control class="control" label="Request">
  <textarea name="request" id="request" rows="3"></textarea>
</app-control>

這降低了維護性。

解決方案

使用 host 設定:

@Component({
  selector: 'app-control',
  imports: [],
  templateUrl: './control.component.html',
  styleUrl: './control.component.css',
  encapsulation: ViewEncapsulation.None,
  host: {
    class: 'control',
  },
})

瀏覽器渲染結果:

<app-control _ngcontent-ng-c350018.. label="title" class="control" ng-reflect-label="Title">
  <label>Title</label>
  <input ...>
</app-control>

這樣就可以直接在元件上套用 control 樣式,避免了多餘的 DOM 結構。

Last updated