Switch html templates dynamically on user action in angular 2

前端 未结 2 585
醉梦人生
醉梦人生 2020-12-13 21:31

With Angularjs 1.x you could easily switch html templates on a button click between edit/readonly modus. The ng-include directive was the key.



        
2条回答
  •  无人及你
    2020-12-13 22:29

    I would leverage ngTemplateOutlet directive to do that.

    Since version of 2.0.0-rc.2 (2016-06-15) context was added to NgTemplateOutlet

    • https://github.com/angular/angular/commit/164a091

    so you can try to use this feature as described in my demo plunker (updated to 4.x.x)

    template.html

    Name Age
    {{contact.name}} {{contact.age}}

    component.ts

    import { Component, ViewChild, TemplateRef } from '@angular/core';
    
    interface Contact {
        id: number;
        name: string;
        age: number
    }
    
    @Component({
        ....
    })
    export class App {
        @ViewChild('displayTmpl') displayTmpl: TemplateRef;
        @ViewChild('editTmpl') editTmpl: TemplateRef;
    
        contacts: Array = [{
                id: 1,
                name: "Ben",
                age: 28
            }, {
                id: 2,
                name: "Sally",
                age: 24
            }, {
                id: 3,
                name: "John",
                age: 32
            }, {
                id: 4,
                name: "Jane",
                age: 40
            }];
    
        selected: Contact;
    
        getTemplate(contact) {
            return this.selected && this.selected.id == contact.id ? 
            this.editTmpl : this.displayTmpl;
        }
    
        editContact(contact) {
            this.selected = Object.assign({}, contact);
        }
    
        saveContact (idx) {
            console.log("Saving contact");
            this.contacts[idx] = this.selected;
            this.reset();
        }
    
        reset() {
            this.selected = null;
        }
    }
    

提交回复
热议问题