>  기사  >  웹 프론트엔드  >  Angle6은 ngContentOutlet을 사용하여 구성 요소 위치 교환을 구현하는 방법(코드 예)

Angle6은 ngContentOutlet을 사용하여 구성 요소 위치 교환을 구현하는 방법(코드 예)

不言
不言앞으로
2018-11-21 11:57:502258검색

이 기사의 내용은 ngContentOutlet을 사용하여 구성 요소 위치 교환(코드 예제)을 구현하는 방법에 대한 것입니다. 필요한 친구가 참고할 수 있기를 바랍니다.

ngContentOutlet 지시문 소개

ngContentOutlet 지시문은 ngTemplateOutlet 지시문과 유사하며 둘 다 동적 구성 요소에 사용된다는 차이점이 있습니다. 후자는 Component를 전달합니다.

사용법 먼저 살펴보기:

MyComponent가 사용자 정의 구성 요소인 경우 이 지침은 자동으로 구성 요소 팩토리를 생성하고 ng-container에 뷰를 생성합니다.

컴포넌트 위치 교환 실현

Angular의 뷰는 데이터에 바인딩되어 있으므로 HTML DOM 요소를 직접 조작하는 것은 권장되지 않으며, 데이터를 변경하는 것이 좋습니다. .

먼저 두 가지 구성요소를 정의합니다.

button.comComponent.ts

import { Component, OnInit } from '@angular/core';
@Component({
 selector: 'app-button',
 template: `<button>按钮</button>`,
 styleUrls: ['./button.component.css']
})
export class ButtonComponent implements OnInit {
 constructor() { }
 ngOnInit() {

text.comComponent.ts

import { Component, OnInit, Input } from '@angular/core';
@Component({
 selector: 'app-text',
 template: `
 <label for="">{{textName}}</label>
 <input type="text">
 `,
 styleUrls: ['./text.component.css']
})
export class TextComponent implements OnInit {
 @Input() public textName = 'null';
 constructor() { }
 ngOnInit() {
 }
}

아래 코드에서는 위의 두 구성 요소를 동적으로 생성하고 위치 교환 기능을 구현합니다.

동적으로 컴포넌트 생성 및 위치 교환 구현

위에서 생성한 두 컴포넌트인 ButtonComponent와 TextComponent를 저장하기 위해 먼저 배열을 생성합니다. 코드는 다음과 같습니다:

import { TextComponent } from './text/text.component';
import { ButtonComponent } from './button/button.component';
import { Component } from '@angular/core';
@Component({
 selector: 'app-root',
 template: `
 <ng-container *ngFor="let item of componentArr" >
  <ng-container *ngComponentOutlet="item"></ng-container>
 </ng-container>
 <br>
 <button (click)="swap()">swap</button>
`,
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 public componentArr = [TextComponent, ButtonComponent];
 constructor() {
 }
 public swap() {
  const temp = this.componentArr[0];
  this.componentArr[0] = this.componentArr[1];
  this.componentArr[1] = temp;
 }
}

위 내용은 Angle6은 ngContentOutlet을 사용하여 구성 요소 위치 교환을 구현하는 방법(코드 예)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제