angular2中“ng-include”的替代方法是什么?

问题描述 投票:8回答:3

是否有任何角度来实现ng-include在angularjs中的作用?

angular
3个回答
2
投票

最接近ng-include的是ngTemplateOutlet指令。您需要将TemplateRef传递给它和可选的上下文。像这样的东西:

@Component({
  selector: 'child',
  template: `
    <div>
      here is child template that includes myTemplate
      <ng-container [ngTemplateOutlet]="myTemplate"></ng-container>
    </div>`
})
export class ChildComponent {
  @Input() myTemplate: TemplateRef<any>;
}


@Component({
  selector: 'app-root',
  template: `
    <p>Parent</p>
    <child [myTemplate]="myTemplate"></child>
    <ng-template #myTemplate>hi julia template!</ng-template>
  `
})
export class AppComponent {
  @ViewChild('myTemplate', {read: TemplateRef}) myTemplate: TemplateRef<any>;
}
  1. 父组件查询模板并将其传递给子组件
  2. 子组件使用ngTemplateOutlet指令来创建视图并对其进行渲染。

1
投票
//ng-include equivalent in Angular2/4
// How to create directive for ng-clude in Angular2/4
import {
    Directive,
    ElementRef,
    Input,
    OnInit
} from '@angular/core';
import {
    Headers,
    Http,
    Response
} from '@angular/http';

@Directive({
    selector: 'ngInclude'
})
export class NgIncludeDirective implements OnInit {

    @Input('src')
    private templateUrl: string;
    @Input('type')
    private type: string;

    constructor(private element: ElementRef, private http: Http) {

    }
    parseTemplate(res: Response) {
        if (this.type == 'template') {
            this.element.nativeElement.innerHTML = res.text();
        } else if (this.type == 'style') {
            var head = document.head || document.getElementsByTagName('head')[0];
            var style = document.createElement('style');
            style.type = 'text/css';
            style.appendChild(document.createTextNode(res.text()));
            head.appendChild(style);
        }
    }
    handleTempalteError(err) {

    }
    ngOnInit() {
        this.
        http.
        get(this.templateUrl).
        map(res => this.parseTemplate(res)).
        catch(this.handleTempalteError.bind(this)).subscribe(res => {
            console.log(res);
        });
    }

}

enter code here

    // html code

    <
    ngInclude src = "{{src}}"
type = "template" > < /ngInclude>

0
投票

从angular2 +方式思考,最好将子模板声明为组件:

@Component({
  selector: 'app-child', 
  template: `
    <ng-container>
      here is child template that includes myTemplate
    </ng-container>`
})
export class ChildComponent {
}


@Component({
  selector: 'app-root',
  template: `
    <p>Parent</p>
    <app-child ></app-child>
  `
})
export class AppComponent {
}
© www.soinside.com 2019 - 2024. All rights reserved.