The basic components of angular2 learning notes and ngfor

Time:2021-2-25

The idea of angular2 is very advanced. It abandons the complex construction mode of angular1 and adopts the method of component-based prescription. Let’s take a look at what a basic component looks like.angular2-demo
The basic components of angular2 learning notes and ngfor

1、 Introduction

1. Directory structure

The basic components of angular2 learning notes and ngfor

  • .tsComponent code

  • .scssstyle

  • .pngdesign sketch

  • .htmltemplate file

2. Renderings

The basic components of angular2 learning notes and ngfor

2、 Code instance

https://github.com/qq83387856/angular2-demo/tree/master/src/ts/component/basic

3、 Detailed interpretation

1. Basic.ts

A basic component looks like it’s not so mysterious

import {Component} from '@angular/core';
import {UserModel} from './../../model/UserModel';

//Create simulation data
let xiaomo:UserModel = new UserModel( 'xiaomo');
let xiaoming:UserModel = new UserModel('xiaoming');

@Component({
    selector: 'basic',
    styles:[require('./ Basic.scss '], // inline style, pay attention to use row loader
    template: require('./Basic.html')
})

export class BasicComponent {

    users:Object;
    //Assignment in constructor
    constructor() {
            this.users= [ xiaomo,xiaoming];
    };
}

2. UserModel.ts

UUID is used to create a random ID as the unique identifier
usepublicYou don’t have tothis.name = name

import { uuid } from './../util/uuid';

export class UserModel{
    id :string;
    constructor(public name:string){
            this.id = uuid();
    }
}

3. Basic.html

Using ngfor loop, index can get index value (starting from 0)

<div>
    <ul *ngFor="let item of users; let i = index">
        <li>{{i+1}} Hello {{item.name}}</li>
    </ul>
</div>