Life Developer
인생 개발자
분류 전체보기 (141)
[Angular]AppRoutingModule로 화면 주소 redirect하기

app.module.ts 를 보면

AppRoutingModule를 import 한다.

여기로 가서 아래처럼 화면주소값이 ''이면 index로 가게 할수 있다.

{

    path : '', - 주소값을 이렇게 지정하면

    redirectTo : 'index', - 여기로 이동해라

    pathMatch : 'full', - 정확히 ''여야 한다. 만약 '123' 이면 정확히 123 이어야 한다.

  },

  {

    path : 'index', - index에 이동하면

    component : AppComponent, - 이것을 실행해라. 는뜻

  }

 

 

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

import { RoutesRouterModule } from '@angular/router';

import { AppComponent } from './app.component';

 

const routesRoutes = [

  {

    path : '',

    redirectTo : 'index',

    pathMatch : 'full',

  },

  {

    path : 'index',

    component : AppComponent

  }

];

 

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

 

  Comments,     Trackbacks
[Angular]module?

module 에 declarations 로 사용 컴포넌트를 정의하며,

imports 해서 module을 참조한다.

declarations에 사용할 컴포넌트가 없는데 사용할수있다?

그것은 module을 import 했기 때문이다.

 

그리고 그 module 역시 module.ts를 보면 experts 한다고 써놨을것이다.

뭐, 이렇게...

exports : [

    TestComponent

  ],

 

의존성 주입이라고도 한다. DI.

어려웠는데 구조를 아는것이 거의 절반 아는것이다...라는걸 느꼈다.

 

아직 앵귤러 실무는 안해봤지만.

 

 

==========================================================

 

@NgModule({

  declarations: [

    AppComponent,

    HelloComponent,

    HeaderComponent,

    FooterComponent,

    SectionComponent,

    TimeDisplayComponent,

    ButtonsComponent,

  ],

  imports: [

    BrowserModule,

    AppRoutingModule,

    LayoutModule

  ],

  exports :[AppComponent],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

  Comments,     Trackbacks
[Angular]export해서 import 하는법

export해서 import 하는법

 

export default 는 하나만 할수 있고 import 할때 중괄호 안쓰고 불러야함.

 

import * as all from './a'; 처럼 * as all 써도됨,

근데 다가져와서 용량 낭비

===============================================



export let aaa=10;

 

export class App{

    

}

 

class Angular{

    namer="angular";

}

 

export class Item{

    itemName="toy";

}

export default Angular;

 

================================================



import {aaaAppfrom './a';

 

console.log(aaa);

 

let app=App;

 

import Angular from './a';

 

let a=new Angular();

a.namer;

 

import {Itemfrom './a';

 

let b=new Item();

b.itemName;

  Comments,     Trackbacks
[Angular]부모의 데이터를 자식에게 넘기기

자식에게 데이터를 받아서 startTime함수를 호출해 아래처럼 데이터를 받았다.

 

 

<div class = 'title'>

<div class = 'display'>

 

    <app-time-display></app-time-display>

    <app-buttons (clickEvent)='startTime($event)'></app-buttons>

 

</div>

</div>

 

 

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

 

@Component({

  selector: 'app-section',

  templateUrl: './section.component.html',

  styleUrls: ['./section.component.scss']

})

export class SectionComponent implements OnInit {

 

  present='welcome';

 

  constructor() { }

 

  startTime(childData){

    this.present=childData;

  }

 

  ngOnInit(): void {

  }

 

}

 

 

 

============================================

받은 데이터를 자식에게 전달해보자.

 

일단 present변수에 값이 있으니 부모 html에서 이렇게 해준다.

 

<div class = 'title'>

<div class = 'display'>

 

    <app-time-display [inputData]='present'></app-time-display>

    <app-buttons (clickEvent)='startTime($event)'></app-buttons>

 

</div>

</div>

 

inputData라는 변수에 present를 받는다는 의미.

 

그럼 inputData를 만들러 가자.(자식에서)

 

inputData를 만드는데 줄때는 @Output을 하였고,

 

지금은 받는것이니 @Input()을 사용한다.(데코레이터)

 

그럼 시작 버튼(데이터를 처음에 준 자식에 있는 버튼)을 클릭하지 않을때가 첫페이지 이므로,

 

ngOnChanges함수엔 welcome이 들어가있을 것이다.(present 초기값)

 

여기서 ngOnChanges 는 Input데이터가 바뀔때마다 작동하는것임.

 

그리고 버튼을 누르면 welcome에서 change!로 바뀐다.

 

다시 누르면 어차피 change!니까 ngOnChanges 함수는 호출이 되지 않는다.

 

 

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

 

@Component({

  selector: 'app-time-display',

  templateUrl: './time-display.component.html',

  styleUrls: ['./time-display.component.scss']

})

export class TimeDisplayComponent implements OnInit {

 

  

  @Input()

  inputData:string;

 

  test=0;

 

  constructor() {

    setInterval(() => {

      this.test++;

    }, 1000)

  }

 

  ngOnChanges(changesSimpleChanges){

    console.log(changes);

  }

 

  ngOnInit(): void {

  }

 

}

'Developer' 카테고리의 다른 글

[Angular]module?  (0) 2020.10.03
[Angular]export해서 import 하는법  (2) 2020.10.03
[Angular]자식의 데이터를 부모에게 넘기기  (0) 2020.10.03
[Angular]click 이벤트 바인딩  (0) 2020.10.03
[typescript]타입가드  (0) 2020.10.02
  Comments,     Trackbacks
[Angular]자식의 데이터를 부모에게 넘기기

클릭했을때 데이터를 넘겨보자.

 

일단 클릭을 하면 start함수를 호출하게끔 설계.

 

 

<p>

    <button class='startBtn' (click)='start()'>시작</button>

    <button class='stopBtn'>멈춤</button>

    <button class='resetBtn'>리셋</button>

</p>

 

 

===============================================

start 함수를 선언을 해야 사용가능.

@Output()을 (데코레이터) 이용해서 emit에 값을 저장함.

 

@Component({

  selector: 'app-buttons',

  templateUrl: './buttons.component.html',

  styleUrls: ['./buttons.component.scss']

})

export class ButtonsComponent implements OnInit {



  @Output() clickEvent = new EventEmitter();

 

  constructor() { }



  start() {

    this.clickEvent.emit(10);

  }

 

  ngOnInit(): void {

  }

 

}

 

일단 여기까지 하면 값은 저장되었음.

 

이걸 부모 컴포넌트에서 뺼수있음.

 

===============================================

만약 자식인 app-buttons 에서 클릭이벤트 발생하면 startTime이란놈 호출함.

이때 파라미터는 $event 여야함. emit에 저장한놈이 여기로 가는거임.

 

 

<div class = 'title'>

<div class = 'display'>

 

    <app-time-display></app-time-display>

    <app-buttons (clickEvent)='startTime($event)'></app-buttons>

 

</div>

</div>

 

그러고 이제 부모 컴포넌트에서 startTime 함수 만들어서 받으면 됨.

 

======================================================

 

이렇게.

 

 

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

 

@Component({

  selector: 'app-section',

  templateUrl: './section.component.html',

  styleUrls: ['./section.component.scss']

})

export class SectionComponent implements OnInit {

 

  constructor() { }

 

  startTime(num){

    console.log('섹션 컴포넌트가 잘 받았다.')

    console.log(num);

  }

 

  ngOnInit(): void {

  }

 

}

 

  Comments,     Trackbacks
[Angular]click 이벤트 바인딩

컴포넌트

 

export class ButtonsComponent implements OnInit {

 

  constructor() { }

 

  test($event:MouseEvent){

    console.log($event);

  }

 

  ngOnInit(): void {

  }

 

}

 

 

HTML

 

<p>

    <button class='startBtn' (click)='test($event)'>시작</button>

    <button class='stopBtn'>멈춤</button>

    <button class='resetBtn'>리셋</button>

</p>

  Comments,     Trackbacks
[typescript]타입가드

추론을 위해 가드친다.

 

 

import { isParameter } from "typescript"

 

interface Person{

    name:string;

    age:number;

}

 

interface Car{

    brand:string;

    wheel:number;

}



function isPerson(param:any):param is Person{

    return isParameter.name !==undefined;

}

 

function hello(obj:Person |Car){

    if(isPerson(obj)){

        console.log(obj.name);

        console.log(obj.age);

    }else{

        console.log(obj.brand);

        console.log(obj.wheel);

    }

}

  Comments,     Trackbacks
[typescript]Decorator - 파라미터에 decorator 붙혀서 통제하기

function print(target:any,methodName:stringparamIndex:number){

    console.log(target);

    console.log(methodName);

    console.log(paramIndex);

}

 

class Person {

    private _namestring;

    private _agenumber;

 

    constructor(namestring, @print agenumber) {

        this._name = name;

        this._age = age;

    }

 

    hello(@print message:string){

        console.log(message);

    }

}

  Comments,     Trackbacks