美文网首页
angular *ngTemplateOutlet使前端代码更有

angular *ngTemplateOutlet使前端代码更有

作者: 饱饱想要灵感 | 来源:发表于2022-06-15 15:56 被阅读0次

    使用方式

    <ng-container *ngTemplateOutlet="模板名称; context: {参数名: 参数值}"></ng-container>
    
    <ng-template #模板名称 let-可以定义一个新的参数名="参数名">
    <span>Hello, {{新的参数名}} !</span>
    </ng-template>
    

    例子

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'ng-template-outlet-example',
      template: `
    <div>
        <ng-container *ngTemplateOutlet="template1"></ng-container>
        <br/>
        <ng-container *ngTemplateOutlet="template2; context: user"></ng-container>
        <br/>
        <ng-container *ngTemplateOutlet="template3; context: {'obj' : user}"></ng-container>
    </div>
    
    <ng-template #template1>
      <p>Hello, world!</p>
    </ng-template>
    
    <ng-template #template2 let-userName="name">
      <p>Nice to meet you, {{userName}}!</p>
    </ng-template>
    
    <ng-template #template3 let-person="obj">
      <p>Bye bye, {{person.age}}!</p>
    </ng-template>
    `
    })
    export class NgTemplateOutletExample {
      user = {name: '饱饱', age: 18};
    }
    

    总结

    这个格式是不是很眼熟? 就像java调用方法一样, 定义参数传递参数;
    如此一来, 即使不定义子组件, 也可以解决元素内容过长, 导致无法阅读的问题

    相关文章

      网友评论

          本文标题:angular *ngTemplateOutlet使前端代码更有

          本文链接:https://www.haomeiwen.com/subject/hrrqvrtx.html