Angular Component and Bind

Create Component

Component is a UI parts. It’s same meaning of other framework, React and Vue

Create Component with ng command

ng g component <componentname>

After this command, following files are generated

NameDescription
<componentname>.component.tsComponent logic
<componentname>.component.cssCSS
<componentname>.component.htmlTemplate HTML
<componentname>.component.spec.tsTest

By default component directory is generated. So, those files are under one directory

Sometimes, this is troublesome. If you create a files without directory, use this

ng g component --flat <componentname>

Simple Bind

Let’s move on next topic. Angular and other framework first topic is Bind.

Populate (calculated) data by javascript. The style is same as Angular JS(Angular 1)

app.component.ts

import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
 
  a = 2;
 
  constructor() { }
 
  ngOnInit() {
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
 
 
import { AppComponent } from './app.component';
@NgModule({
  imports: [
    CommonModule,
    BrowserModule,
    FormsModule
  ],
  declarations: [AppComponent ],
  bootstrap: [AppComponent]
})
export class AppModule { }

main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 
// import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
 
import { AppModule } from './app/bind/app.module';
 
if (environment.production) {
  enableProdMode();
}
 
platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

app.component.html

<p>
  hello works!
</p>
<p>
  {{a}}
</p>

Build and access html, you can see {{a}} as 2

コメント