Angular 2 : multiple HTML pages within same component

佐手、 提交于 2019-11-29 10:07:54

Try do like this :

@Component({
    selector: 'register-page',
    template: `
            <div class="open-card-BG" *ngIf="registerView == 'regView1'">Reg View 1 Content</div>
            <div class="open-card-BG" *ngIf="registerView == 'regView2'">Reg View 2 Content</div>
            `,
    styleUrls: ['./register-page.component.scss'],
    providers: [RegisterService, Configuration, LocalStorageService]
})

export class Appcomponent {
    registerView = 'regView1';
}

Else do like this

page1.component.html

<div>
    <h1>Page1 Component Content</h1>
</div>

page2.component.html

<div>
    <h1>Page2 Component Content</h1>
</div>

home.component.html

<div>
    <div class="open-card-BG" *ngIf="registerView == 'regView1'">
         <app-page1-component></app-page1-component>
    </div>
    <div class="open-card-BG" *ngIf="registerView == 'regView2'">
         <app-page2-component></app-page2-component>
    </div>
</div>

component.ts

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})

export class HomeComponent {
    registerView = 'regView1';
}

In Angular components are basically a patch of the screen means there should always be single template for each component class. If you want to use multiple templates for single component class then As per terminology it doesn't refer to component definition. If you want to use then create a base class and create 3 separate component and extend the base class.

Using *ngIf would be the most sensible way to do this. If it gets to the point that you are having to use *ngIf to cover large chunks of HTML then it's probably more of an indication that these should be separate components since they clearly have significantly different views.

If there is a lot of shared logic in your .ts files you can make a class with all the shared logic and use class inheritance on your individual components.

export class BaseComponentLogic implements OnInit {

    ...

}

@Component({...})
export class MyFirstComponent extends BaseComponentLogic implements OnInit {

   ...
}

@Component({...})
export class MySecondComponent extends BaseComponentLogic implements OnInit {

   ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!