简体   繁体   中英

Angular2 app.component removing all content from page

I've been working on an .net core app and I'm trying to now add angular2 to the project and I'm a bit confused as to why the app.component template appears to remove everything from the page even though when inspecting the page, the original content is indeed there. My understanding was that the app.component provided an entry point in the same way that the following does in angular1:

var app = angular.module('myApp', []);

<html ng-app="app">....</html>

Is there anyway I can use angular2 without having to abandon my razor views, or am I going to have to bootstrap every view?

In angular 2 you need to have one Root component which will be used for bootstrapping and will be rendered in index.html. Al other components, services needs to be imported and declared in modules.ts Ex: Sample app below has three components: Parent, App and New App. In modules.ts file you need to import all the components and declare inside NgModules. Below that it is bootstrapping Parent component.

Modules.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule }   from '@angular/router';

import { ParentComponent } from './parent.component';
import { AppComponent } from './app.component';
import { NewAppComponent } from './newapp.component';

@NgModule({
declarations: [
ParentComponent, AppComponent, NewAppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
  { path: 'app', component: AppComponent },
  { path: 'newapp', component: NewAppComponent }
],{ useHash: true })
],
 providers: [],
 bootstrap: [ParentComponent]
})
export class AppModule { }

Parent.Component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'parent-root',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
}

Parent.Component.Html

<h1>Test</h1>  
<ul>
    <li><a href="/index.html#/app">App</a></li>
    <li><a href="/index.html#/newapp">New App</a></li>
    </ul>
   <router-outlet></router-outlet>

Index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Routingapp</title>
  <base href="/index.html">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <parent-root>Loading...</parent-root>
</body>
</html>

Parent component is just used to bootstrap the application (It can be considered as the Home page of you application). There is no need to bootstrap every view/component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM