如何使用多个ng-templates创建Angular 6组件?

时间:2018-08-22 23:51:26

标签: angular templates angular2-template markup

关于Angular的模板,我已经读了很多东西,但是我没有找到任何与我要归档的东西非常相似的东西,更不用说Angular 2+中的模板令人困惑,因为这并没有这项任务比应做的要容易。

我想知道如何做这样的事情(或者甚至有可能):

<my-form>
  <ng-template [for]="title">Users</ng-template>
  <ng-template [for]="content">
    <form>
      <input type="text" name="username">
      <input type="text" name="password">
    </form>
  </ng-template>
  <ng-template [for]="footer">
    <button (click)="edit()">Edit</button>
    <button (click)="delete()">Delete</button>
  </ng-template>
</my-form>

因此,我的想法是我的my-form组件将具有诸如标记,样式和常见内容之类的内容,这些内容将适用于我要在应用程序中创建的所有这些“常见表格”。我整日都在搜索,但都没找到结果,this article就像 kinda 一样,但还没结束,对我来说,这篇文章也很难理解

注意:我什至不知道[for]标签是否正确,这已经超出了我的脑海。自定义标签会起作用(例如<my-form-title></my-form-title><my-form-content></my-form-content><my-form-footer></my-form-footer>等)。

这里有人可以帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

每个Angular结构指令都使用ng-template转换它所附加的元素,因此您可以使用自定义指令将“孩子”标记为模板。

首先,为组件的可自定义部分创建一堆指令:

import re

class PersonalDetails:
    def __init__(self, personal_details):
        self.personal_details = personal_details

    def set_gender(self):
        self.gender = 'Male'

    def set_age(self):
        self.age = 22

    def execute_all_settings(self):
        '''
        wrapper for setting all variables that start with set.
        Will skip anything not matching regex '^set'
        '''
        to_execute = [i for i in dir(self) if re.search('^set', i)]
        print(to_execute)
        for func_name in to_execute:
            getattr(self, func_name)()

pd = PersonalDetails('') 
pd.execute_all_settings() 
print(pd.gender)
# ['set_age', 'set_gender']
# Male

您使用@Directive({ selector: '[myFormTitle]' }) export class TitleDirective {} @Directive({ selector: '[myFormContent]' }) export class ContentDirective {} @Directive({ selector: '[myFormFooter]' }) export class FooterDirective {} 查询组件树以获取由这些指令创建的模板:

@ContentChild

然后像往常一样在组件模板中渲染它们:

@Component({
  selector: 'my-form',
  templateUrl: './my-form.component.html',
})
export class MyFormComponent implements OnInit {
  @ContentChild(TitleDirective, {read: TemplateRef})
  titleTemplate: TemplateRef<any>;

  @ContentChild(ContentDirective, {read: TemplateRef})
  contentTemplate: TemplateRef<any>;

  @ContentChild(FooterDirective, {read: TemplateRef})
  footerTemplate: TemplateRef<any>;

  constructor() { 
  }

  ngOnInit() {
    console.log(this)
  }
}

您可以像这样使用此组件:

<form>
  <h1>
    <ng-container *ngTemplateOutlet="titleTemplate"></ng-container>
  </h1>
  <hr/>
  <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
  <hr/>
  <small>
    <ng-container *ngTemplateOutlet="footerTemplate"></ng-container>
  </small>
</form>

如果要将上下文传递给模板,也可以在<my-form> <span *myFormTitle>BIG LETTERS</span> <div *myFormContent> <label>Name: <input name='name'/></label> </div> <span *myFormFooter> yadda blah </span> </my-form> 等属性中使用指令Sheets REST API。或访问继承的上下文。我不会在这里进行深入探讨,因为它实际上并不适合您的用例。