Embedding an Angular Directive in

2019-07-19 06:38发布

I'm trying to get an angular directive to repeat inside a <tr>. Without the directive, the code is

<tr *ngFor='let cluster of clusters'>
    <td style='display: flex; flex-direction: column; width: 40%; min-width: 300px;'>
        <span>{{ cluster.Name }}</span>
        <span>{{ cluster.StatusMessage }}</span>
    </td>
    <td style='width: 100%;'>
        ...
    </td>
</tr>

And looks like

enter image description here

When I refactor the directive, I lose the <tr> formatting. The refactored code is

<tr *ngFor='let cluster of clusters'>
    <cluster-row [name]='cluster.Name' [statusMessage]='cluster.StatusMessage'></cluster-row>
</tr>

The cluster-row component code is:

<td style='display: flex; flex-direction: column; width: 40%; min-width: 300px;'>
    <span>{{ name }}</span>
    <span>{{ statusMessage }}</span>
</td>
<td style='width: 100%;'>
    ...
</td>

It works, but the <tr> formatting goes away.

enter image description here

The developer tools show a <tr> with a <cluster-row> nested in it, and two <td>s nested in that, as I would expect.

1条回答
祖国的老花朵
2楼-- · 2019-07-19 07:22

<tr> can't contain a <cluster-row> element.

You can use an attribute selector instead like

<tr *ngFor='let cluster of clusters'>
    <td cluster-row [name]='cluster.Name' [statusMessage]='cluster.StatusMessage'></cluster-row>
</tr>

with

@Component({
//@Directive({
  selector: '[cluster-row]'

The component or directive then is the <td>, therefore you can't repeat it inside the components template

style='display: flex; flex-direction: column; width: 40%; min-width: 300px;'

can just be added to

@Component({ 
  selector: '[cluster-row]',
  styles: [...],
查看更多
登录 后发表回答