導入
子コンポーネントに外から値を渡せると、同じ部品を「中身だけ変えて」使い回せます。受け取り口を @Input で作ります。
説明
CardComponent が title を @Input で受け取り、親が [title]="..." で渡します。
@Component({
selector: 'app-card',
standalone: true,
template: `<div style="border:1px solid #ccc; padding:8px; margin:4px; border-radius:8px">
<b>{{ title }}</b>
</div>`,
})
class CardComponent {
@Input() title: string = '';
}
@Component({
selector: 'app-root',
standalone: true,
imports: [CardComponent],
template: `
<app-card [title]="'りんご'"></app-card>
<app-card [title]="'みかん'"></app-card>
<app-card [title]="favorite"></app-card>
`,
})
class AppComponent {
favorite: string = 'ぶどう';
}
@Input() title… 「外から受け取れるプロパティ」を宣言します。- 親側は
[title]="'りんご'"のようにプロパティバインディングで渡します(文字列リテラルは' 'で囲みます)。 [title]="favorite"のように、親のプロパティを渡すこともできます。
やってみよう
CardComponent に color の @Input を追加し、[style.color]="color" でカードの文字色を親から指定してみましょう。