Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 角度2使用“a”;模板";用于在组件循环内使用ng内容_Html_Angular - Fatal编程技术网

Html 角度2使用“a”;模板";用于在组件循环内使用ng内容

Html 角度2使用“a”;模板";用于在组件循环内使用ng内容,html,angular,Html,Angular,我正在尝试创建一个组件,该组件将执行一些操作并在结果集上循环。我希望能够为循环结果集中的项目提供一个“模板” 例如,这就是我想要的想法: <search-field> <ng-template let-item> <span><strong>{{item.foo}}</strong></span> <span>{{item.bar}}</span> &l

我正在尝试创建一个组件,该组件将执行一些操作并在结果集上循环。我希望能够为循环结果集中的项目提供一个“模板”

例如,这就是我想要的想法:

<search-field>
    <ng-template let-item>
        <span><strong>{{item.foo}}</strong></span>
        <span>{{item.bar}}</span>
    </ng-template>
</search-field>

如何将循环的每个项目传递给ng内容,以便在第一个示例的代码中访问它?

通过以下方法解决了这一问题:

组件模板用法:

<search-field>
    <ng-template let-item>
        <span><strong>{{item.username}}</strong></span>
        <span>{{item.email}}</span>
    </ng-template>
</search-field>

{{item.username}}
{{item.email}
组件模板定义:

<div class="search-container">
    <div class="search-input">
        <input type="text" class="form-control" placeholder="Search users..." [(ngModel)]="searchString" (ngModelChange)="searchStringChanged($event)">
        <div class="md-icon">search</div>
    </div>

    <ul class="search-results" *ngIf="searchResults.length > 0">
        <li class="search-results__item" *ngFor="let item of searchResults">
            <ng-template [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{$implicit: item}"></ng-template>
        </li>
    </ul>
</div>

搜索
组件类别:

@Component({...})
export class SearchFieldComponent {
    @ContentChild(TemplateRef) templateRef: TemplateRef<any>;

    // ...
}
@组件({…})
导出类SearchFieldComponent{
@ContentChild(TemplateRef)TemplateRef:TemplateRef;
// ...
}
解释:

使用
ng template
,我可以使用
let item
语法,其中
item
是循环每次迭代时将传递到模板中的数据

为了实现上述功能,在
搜索字段
组件中,我使用
ng template
ngTemplateOutlet
作为模板引用,并且
ngTemplateOutletContext
被赋予值
{$implicit:item}
,其中
item
是我想要传递到模板中的数据


最后,在component类中,我需要使用
ContentChild
来获取要在
ngTemplateOutlet
中使用的模板的引用,谢谢!这种方法还解决了嵌套的自定义组件
@Component({...})
export class SearchFieldComponent {
    @ContentChild(TemplateRef) templateRef: TemplateRef<any>;

    // ...
}