목차
부모 컴포넌트 => 자식 컴포넌트
@input, 가장 일반적으로 사용되는 방법
{{textContent}}
setter
onChange
@ViewChild()
로컬 변수
子组件 => 父组件
@output()
Rxjs
웹 프론트엔드 JS 튜토리얼 각도 컴포넌트 통신 분석

각도 컴포넌트 통신 분석

Jul 14, 2018 am 09:27 AM
css html html5 javascript

이 기사에서는 특정 참조 가치가 있는 각도 구성 요소 통신에 대한 분석을 주로 소개합니다. 이제 모든 사람과 공유합니다. 필요한 친구가 참조할 수 있습니다.

이 기사에는 주로 다음과 같은 유형의 단일 페이지 응용 프로그램 구성 요소 통신이 있습니다. Angular 통신에 대해 이야기해 보세요

각도 컴포넌트 통신 분석

  1. 상위 구성 요소 => 하위 구성 요소

  2. 하위 구성 요소 => 상위 구성 요소

  3. 구성 요소 A = >

    상위 구성요소= > ; 하위 구성 요소
하위 구성 요소 => 상위 구성 요소 sibling => 상위 구성 요소 삽입 ngOnChanges() (사용되지 않음)지역 변수@ViewChild()serviceRxjs용 ObservalbelocalStorage, sessionStoragelocalStorage,sessionStorage




service service

Rxjs용 Observalbe
Rxjs용 Observalbe

localStorage,sessionStorage

위 차트는 사용할 수 있는 통신 솔루션을 요약한 것입니다. Rxjs는 redux와 promise를 포함하여 가장 강력한 사용법입니다. 기능적 상태 관리, 하나씩 이야기해 볼까요

부모 컴포넌트 => 자식 컴포넌트

@input, 가장 일반적으로 사용되는 방법

@Component({
  selector: 'app-parent',
template: '<p>childText:<app-child></app-child></p>',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  varString: string;
  constructor() { }
  ngOnInit() {
    this.varString = '从父组件传过来的' ;
  }
}
로그인 후 복사
import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '<h1 id="textContent">{{textContent}}</h1>',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() public textContent: string ;
  constructor() { }
  ngOnInit() {
  }
}
로그인 후 복사

setter

setter는 @input 속성을 가로채는 것입니다. 왜냐하면 우리가 통신할 때 컴포넌트의 경우, 입력 속성을 처리해야 하는 경우가 많으며, 이는 Setter와 Getter가 함께 사용되는 경우가 많습니다. 위의 child.comComponent.ts
child.comComponent.ts

import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '<h1 id="textContent">{{textContent}}</h1>',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
_textContent:string;
  @Input()
  set textContent(text: string){
   this._textContent = !text: "啥都没有给我" ? text ;
  } ;
  get textContent(){
  return this._textContent;
  }
  constructor() { }
  ngOnInit() {
  }
}
로그인 후 복사

onChange

를 약간 수정하면 이는 각도를 통해 감지됩니다. 라이프 사이클 후크를 사용하는 것은 권장되지 않습니다. 사용하려면 각도 문서를 참조하세요.

@ViewChild()

@ViewChild()는 일반적으로 하위 구성 요소의 비공개 메서드를 호출하는 데 사용됩니다.

           import {Component, OnInit, ViewChild} from '@angular/core';
       import {ViewChildChildComponent} from "../view-child-child/view-child-child.component";
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent implements OnInit {
      varString: string;
      @ViewChild(ViewChildChildComponent)
      viewChildChildComponent: ViewChildChildComponent;
      constructor() { }
      ngOnInit() {
        this.varString = '从父组件传过来的' ;
      }
      clickEvent(clickEvent: any) {
        console.log(clickEvent);
        this.viewChildChildComponent.myName(clickEvent.value);
      }
    }
로그인 후 복사
      import { Component, OnInit } from '@angular/core';
    @Component({
      selector: 'app-view-child-child',
      templateUrl: './view-child-child.component.html',
      styleUrls: ['./view-child-child.component.css']
    })
    export class ViewChildChildComponent implements OnInit {
      constructor() { }
      name: string;
      myName(name: string) {
          console.log(name);
          this.name = name ;
      }
      ngOnInit() {
      }
    }
로그인 후 복사

로컬 변수

로컬 변수는 viewChild와 유사합니다. HTML 템플릿에서만 사용할 수 있습니다. parent.comComponent.html을 수정하고 #viewChild 변수를 사용하여 하위 구성 요소를 나타낼 수 있습니다. 하위 구성 요소의 메서드를 호출합니다.#viewChild这个变量来表示子组件,就能调用子组件的方法了.

<p>
    <input>
    <button>局部变量传值</button>
    <app-view-child-child></app-view-child-child>
            </p>
로그인 후 복사

child 组件如下

@Component({
  selector: 'app-view-child-child',
  templateUrl: './view-child-child.component.html',
  styleUrls: ['./view-child-child.component.css']
})
export class ViewChildChildComponent implements OnInit {

  constructor() { }
  name: string;
  myName(name: string) {
      console.log(name);
      this.name = name ;
  }
  ngOnInit() {
  }

}
로그인 후 복사

子组件 => 父组件

@output()

output这种常见的通信,本质是给子组件传入一个function,在子组件里执行完某些方法后,再执行传入的这个回调function

parent.component.ts
@Component({
  selector: 'app-child-to-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ChildToParentComponent implements OnInit {

  childName: string;
  childNameForInject: string;
  constructor( ) { }
  ngOnInit() {
  }
  showChildName(name: string) {
    this.childName = name;
  }
}
로그인 후 복사
하위 구성 요소는 다음과 같습니다

<p>
  </p><p>output方式 childText:{{childName}}</p>
  <br>
  <app-output-child></app-output-child>
로그인 후 복사
Child 구성 요소=> 상위 구성 요소

@output()

출력, 이 일반적인 통신은 본질적으로 함수를 전달하는 것입니다. code>를 하위 컴포넌트에 추가하고 하위 컴포넌트에서 실행합니다. 특정 메서드를 완료한 후 전달된 콜백 함수를 실행하고 그 값을 상위 컴포넌트에 전달합니다

  child.component.ts
  export class OutputChildComponent implements OnInit {
  // 传入的回调事件
  @Output() public childNameEventEmitter: EventEmitter<any> = new EventEmitter();
  constructor() { }
  ngOnInit() {
  }
  showMyName(value) {
    //这里就执行,父组件传入的函数
    this.childNameEventEmitter.emit(value);
  }
}</any>
로그인 후 복사

parent.comComponent.html

export class OutputChildComponent implements OnInit {
  // 注入父组件
  constructor(private childToParentComponent: ChildToParentComponent) { }
  ngOnInit() {
  }
  showMyName(value) {
    this.childToParentComponent.childNameForInject = value;
  }
}
로그인 후 복사
user.service.ts
@Injectable()
export class UserService {
  age: number;
  userName: string;
  constructor() { }
}
app.module.ts
@NgModule({
  declarations: [
    AppComponent,
    SiblingAComponent,
    SiblingBComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }
SiblingBComponent.ts
@Component({
  selector: 'app-sibling-b',
  templateUrl: './sibling-b.component.html',
  styleUrls: ['./sibling-b.component.css']
})
export class SiblingBComponent implements OnInit {
  constructor(private userService: UserService) {
    this.userService.userName = "王二";
  }
  ngOnInit() {
  }
}
SiblingAComponent.ts
@Component({
  selector: 'app-sibling-a',
  templateUrl: './sibling-a.component.html',
  styleUrls: ['./sibling-a.component.css']
})
export class SiblingAComponent implements OnInit {
  userName: string;
  constructor(private userService: UserService) {
  }
  ngOnInit() {
    this.userName = this.userService.userName;
  }
}
로그인 후 복사

inject into the parent Component

이 원칙을 적용한 이유는 하위 컴포넌트의 필수 생명주기인 부모가 동일하기 때문입니다

import {Injectable} from "@angular/core";
import {Subject} from "rxjs/Subject";
@Injectable()
export class AlertService {
  private messageSu = new Subject<string>();  //
  messageObserve = this.messageSu.asObservable();
  private  setMessage(message: string) {
    this.messageSu.next(message);
  }
  public success(message: string, callback?: Function) {
    this.setMessage(message);
    callback();
  }
}</string>
로그인 후 복사

sibling 컴포넌트 => sibling 컴포넌트


service

Rxjs

는 service

를 통해 통신합니다. 각도의 서비스는 싱글톤이므로 세 가지 통신 유형 모두 서비스를 전달할 수 있습니다. 많은 프런트 엔드는 싱글톤을 매우 명확하게 이해하지 못합니다. 핵심은 서비스를 모듈에 주입할 때 이 모듈의 모든 구성 요소가 속성을 얻을 수 있다는 것입니다. 및 이 서비스의 메소드는 공유되므로 app.moudule .ts 주입 로그 서비스, http 차단 서비스, 하위 모듈에 주입된 서비스, 이 하위 모듈에서만 공유할 수 있는 서비스, 주입된 서비스에서 자주 발견됩니다. 컴포넌트에서는 하위 컴포넌트만 서비스를 얻을 수 있습니다. 다음은 app.module.ts에 삽입되어 서비스를 시연합니다

@Component({
  selector: 'app-sibling-a',
  templateUrl: './sibling-a.component.html',
  styleUrls: ['./sibling-a.component.css']
})
export class SiblingAComponent implements OnInit {
  userName: string;
  constructor(private userService: UserService, private alertService: AlertService) {
  }
  ngOnInit() {
    this.userName = this.userService.userName;
    // 改变alertService的信息源
    this.alertService.success("初始化成功");
  }
}
로그인 후 복사

Rx.js를 통한 통신

이것은 가장 멋진 스트리밍 파일 처리입니다. 구독 게시에 따르면 구독 소스가 변경되면 구독자가 이 변경 사항을 얻을 수 있습니다. 이는 b.js, c.js 및 d.js가 특정 변경 사항을 구독한다는 것입니다. a.js, b.js, c.js, d.js의 값은 즉시 변경되지만 a.js는 b.js, c.js 및 d.js의 메서드를 적극적으로 호출하지 않습니다. 간단한 예를 들자면, 각 페이지에서 ajax 요청을 처리할 때 팝업 프롬프트 메시지가 나오는데, 일반적으로

컴포넌트의 템플릿에 프롬프트 상자 컴포넌트를 넣는데, 이는 매우 번거롭고 한 번만 수행해야 합니다. 각 컴포넌트를 Rx.js 기반으로 한다면 app.comComponent.ts에 이 프롬프트 컴포넌트를 넣으면 app.comComponent.ts가 공개 서비스에 가입하기가 더 쉽습니다

먼저 앨범을 생성하세요. .service.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  message: string;
  constructor(private alertService: AlertService) {
    //订阅alertServcie的message服务
     this.alertService.messageObserve.subscribe((res: any) => {
      this.message = res;
    });
  }
}
로그인 후 복사

sibling-a.comComponent.ts

rrreee

app.comComponent.ts

rrreee

이 방법으로 구독자는 릴리스 소스에 따라 동적으로 변경할 수 있습니다

요약: 위는 일반적으로 사용되는 통신 방법입니다. 다양한 시나리오에 메소드를 적용할 수 있습니다

관련 권장 사항: 🎜🎜🎜Angular-UI Bootstrap 구성 요소를 사용하여 경고를 구현하는 방법🎜🎜🎜

위 내용은 각도 컴포넌트 통신 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Vue에서 부트 스트랩을 사용하는 방법 Vue에서 부트 스트랩을 사용하는 방법 Apr 07, 2025 pm 11:33 PM

vue.js에서 bootstrap 사용은 5 단계로 나뉩니다 : Bootstrap 설치. main.js.의 부트 스트랩 가져 오기 부트 스트랩 구성 요소를 템플릿에서 직접 사용하십시오. 선택 사항 : 사용자 정의 스타일. 선택 사항 : 플러그인을 사용하십시오.

HTML, CSS 및 JavaScript의 역할 : 핵심 책임 HTML, CSS 및 JavaScript의 역할 : 핵심 책임 Apr 08, 2025 pm 07:05 PM

HTML은 웹 구조를 정의하고 CSS는 스타일과 레이아웃을 담당하며 JavaScript는 동적 상호 작용을 제공합니다. 세 사람은 웹 개발에서 의무를 수행하고 화려한 웹 사이트를 공동으로 구축합니다.

부트 스트랩에 분할 라인을 작성하는 방법 부트 스트랩에 분할 라인을 작성하는 방법 Apr 07, 2025 pm 03:12 PM

부트 스트랩 분할 라인을 만드는 두 가지 방법이 있습니다 : 태그를 사용하여 수평 분할 라인이 생성됩니다. CSS 테두리 속성을 사용하여 사용자 정의 스타일 분할 라인을 만듭니다.

H5는 무엇을 언급합니까? 맥락 탐색 H5는 무엇을 언급합니까? 맥락 탐색 Apr 12, 2025 am 12:03 AM

h5referstohtml5, apivotaltechnologyinwebdevelopment.1) html5introducesnewelements 및 dynamicwebapplications.2) itsupp ortsmultimediawithoutplugins, enovannangeserexperienceacrossdevices.3) SemanticLementsImproveContentsTructUreAndSeo.4) H5'Srespo

HTML, CSS 및 JavaScript 이해 : 초보자 안내서 HTML, CSS 및 JavaScript 이해 : 초보자 안내서 Apr 12, 2025 am 12:02 AM

WebDevelopmentReliesonHtml, CSS 및 JavaScript : 1) HtmlStructuresContent, 2) CSSSTYLESIT, 및 3) JAVASCRIPTADDSINGINTERACTIVITY, BASISOFMODERNWEBEXPERIENCES를 형성합니다.

부트 스트랩 크기를 조정하는 방법 부트 스트랩 크기를 조정하는 방법 Apr 07, 2025 pm 03:18 PM

부트 스트랩에서 요소의 크기를 조정하려면 다음을 포함하여 차원 클래스를 사용할 수 있습니다.

부트 스트랩을위한 프레임 워크를 설정하는 방법 부트 스트랩을위한 프레임 워크를 설정하는 방법 Apr 07, 2025 pm 03:27 PM

부트 스트랩 프레임 워크를 설정하려면 다음 단계를 따라야합니다. 1. CDN을 통해 부트 스트랩 파일 참조; 2. 자신의 서버에서 파일을 다운로드하여 호스팅하십시오. 3. HTML에 부트 스트랩 파일을 포함; 4. 필요에 따라 Sass/Less를 컴파일하십시오. 5. 사용자 정의 파일을 가져옵니다 (선택 사항). 설정이 완료되면 Bootstrap의 그리드 시스템, 구성 요소 및 스타일을 사용하여 반응 형 웹 사이트 및 응용 프로그램을 만들 수 있습니다.

부트 스트랩에 사진을 삽입하는 방법 부트 스트랩에 사진을 삽입하는 방법 Apr 07, 2025 pm 03:30 PM

Bootstrap에 이미지를 삽입하는 방법에는 여러 가지가 있습니다. HTML IMG 태그를 사용하여 이미지를 직접 삽입하십시오. 부트 스트랩 이미지 구성 요소를 사용하면 반응 형 이미지와 더 많은 스타일을 제공 할 수 있습니다. 이미지 크기를 설정하고 IMG-Fluid 클래스를 사용하여 이미지를 적응할 수 있도록하십시오. IMG 통과 클래스를 사용하여 테두리를 설정하십시오. 둥근 모서리를 설정하고 IMG 라운드 클래스를 사용하십시오. 그림자를 설정하고 그림자 클래스를 사용하십시오. CSS 스타일을 사용하여 이미지를 조정하고 배치하십시오. 배경 이미지를 사용하여 배경 이미지 CSS 속성을 사용하십시오.

See all articles