컴포넌트와 디렉티브의 차이점은 무엇입니까?
Angular 2로 작업을 시작했습니다.
Angular 2의 구성 요소와 지시문의 차이점은 무엇입니까?
기본적으로 문서에 따라 Angular2에는 세 가지 유형의 지시문이 있습니다.
- 구성 요소
- 구조적 지시문
- 속성 지시문
구성 요소
또한 Angular2에서 가장 유명한 디렉티브 유형 인 템플릿, 스타일, 로직 부분이있는 디렉티브 유형입니다. 이 유형의 지시문에서는 @Component
다음과 같이 주석 에 사용자 정의 또는 내장 지시문을 사용할 수 있습니다 .
@Component({
selector: "my-app"
directives: [custom_directive_here]
})
보기에서이 지시문을 다음과 같이 사용하십시오.
<my-app></my-app>
구성 요소 지시문의 경우 여기 에서 최고의 자습서를 찾았 습니다.
구조적 지시문
추천 *ngFor
하고 *ngIf
, DOM 요소를 추가 및 제거하여 DOM 레이아웃을 변경하기 위해 사용된다. 여기에 설명
속성 지시문
일부 기능 / 로직을 적용하여 기존 요소에 사용자 정의 동작 또는 스타일을 부여하는 데 사용됩니다. Like ngStyle
는 요소에 동적으로 스타일을 부여하는 속성 지시문입니다. 우리는 우리 자신의 지시문을 만들고 이것을 미리 정의 된 요소 나 사용자 정의 요소의 속성으로 사용할 수 있습니다. 다음은 간단한 지시문의 예입니다.
먼저 지시문을 가져와야합니다. @angular/core
import {Directive, ElementRef, Renderer, Input} from '@angular/core';
@Directive({
selector: '[Icheck]',
})
export class RadioCheckbox {
// custom logic here...
}
아래와 같이 뷰에서 사용할 수 있습니다.
<span Icheck>HEllo Directive</span>
자세한 정보는 여기 와 여기 에서 공식 튜토리얼을 읽을 수 있습니다.
구성 요소에는 고유 한보기 (HTML 및 스타일)가 있습니다. 지시문은 기존 요소 및 구성 요소에 추가 된 "동작"일뿐입니다.
Component
확장 Directive
합니다.
이 때문에 호스트 요소에는 하나의 구성 요소 만있을 수 있지만 지시문은 여러 개입니다.
구조적 지시문은 <template>
요소에 적용되는 지시문이며 콘텐츠를 추가 / 제거하는 데 사용됩니다 (템플릿 스탬프). *
같은 지시어 애플리케이션은 *ngIf
원인이 <template>
태그를 암시 적으로 생성 할 수 있습니다.
Günter가 말한 것을 완료하기 위해 두 가지 종류의 지시문을 구분할 수 있습니다.
- 구조들 추가하거나 요소를 제거하여 DOM 레이아웃을 업데이트합니다. 두 가지 일반적인 것은
NgFor
및NgIf
입니다. 이러한 항목은 템플릿 개념에 연결되며*
. 자세한 내용은이 링크의 "템플릿 및 *"섹션을 참조하십시오. http://victorsavkin.com/post/119943127151/angular-2-template-syntax - 속성들 그들이 하나를 부착 요소의 모양의 동작을 업데이트합니다.
도움이 되었기를 바랍니다, Thierry
Angular 2는 아키텍처의 구성 요소 / 서비스 모델을 따릅니다.
각도 2 응용 프로그램은 구성 요소로 구성됩니다. 구성 요소는 화면의 일부를 제어하는 HTML 템플릿과 구성 요소 클래스 (타입 스크립트 클래스)의 조합입니다.
모범 사례를 위해 구성 요소 클래스는 각 뷰에 대한 데이터 바인딩에 사용됩니다. 양방향 데이터 바인딩은 각도 프레임 워크에서 제공하는 훌륭한 기능입니다.
제공된 선택기 이름을 사용하여 응용 프로그램에서 구성 요소를 재사용 할 수 있습니다.
구성 요소는 템플릿이있는 일종의 지시문이기도합니다.
다른 두 가지 지침은 다음과 같습니다.
구조적 지시문-DOM 요소를 추가 및 제거하여 DOM 레이아웃을 변경합니다. 예 :
NgFor
및NgIf
.속성 지시문-요소, 구성 요소 또는 다른 지시문의 모양이나 동작을 변경합니다. 전의:
NgStyle
실제 정의는 다음과 같습니다.
- 그것은이있는 경우 템플릿을 , 그것은이다 구성 요소
- 그렇지 않으면 대괄호 "[likethis]" 안에 선택자가 있으면 속성 지시문입니다.
- 그렇지 않으면 구조적 지침 입니다.
다른 정의는 잘못되었습니다.
요약:
컴포넌트는 연관된 뷰 (예 : 렌더링 할 HTML)가있는 지시문입니다. 모든 구성 요소는 지시문이지만 모든 지시문이 구성 요소는 아닙니다. 지시문에는 세 가지 유형이 있습니다.
- 구성 요소 : 관련 동작이있는보기입니다. 이 유형의 지시문은 실제로 DOM 요소를 추가합니다.
- 속성 지시문 : 요소의 모양이나 동작을 수정하기 위해 DOM 요소 (및 DOM 요소이므로 구성 요소)에 연결할 수 있습니다.
- 구조적 지시문 : DOM 레이아웃을 수정하기 위해 DOM 요소 (및 DOM 요소이므로 구성 요소)에 연결할 수 있습니다. 구조적 지시문은 *로 시작하고 실제로 DOM 요소를 추가하거나 제거합니다. 예를 들어
*ngIf
DOM 요소 (또는 사용자 정의 DOM 요소이지만 여전히 DOM 요소 인 각도 구성 요소)를 삽입하거나 제거 할 수 있습니다.
예:
import { Component, HostListener, HostBinding, Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
@Component({
selector: 'app-root',
template: `
<div *ngIf='myBool' appHighlight>Hi there</div>
`,
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
myBool:boolean = true;
}
위의 예에서 다음을 관찰 할 수 있습니다.
- 구성 요소
AppComponent
에는<div>
여기에 표시 되는 요소 가있는 템플릿 이 있습니다. - 속성 지시문 HighlightDirective는
<div>
요소에 있습니다. 즉,<div>
요소 의 동작을 조작합니다 . 이 경우 텍스트가 강조 표시되고 노란색으로 바뀝니다. - The structural directive
*ngIf
is also located on the<div>
element and will determine if the element is to be inserted. The<div>
will be conditionally shown depending on whether the expressionmyBool
can be coerced totrue
.
Actually components are also directives, but have differences between them.
Attribute Directives :
Attribute directives are classes that are able to modify the behavior or appearance of a single element. For creating an attribute directive apply the @Directive
to a class.
import { Directive, ElementRef } from "@angular/core";
@Directive({
selector: "[custom-attr]", })
export class CustomAttrDirective {
constructor(element: ElementRef) {
element.nativeElement.classList.add("bg-success", "text-white");
}
}
Adding a directive attribute template.html File
<tr *ngFor="let item of getProducts(); let i = index" custom-attr>
<td>{{i + 1}}</td>
<td>{{item.name}}</td>
</tr>
Structural Directives :
Structural directives change the layout of the HTML document by adding and removing elements, as a micro-templates. Structural directives allow content to be added conditionally based on the result of an expression such as*ngIf
or for the same content to be repeated for each object in a data source such as *ngFor
.
You can use the built-in directives for common tasks, but writing custom structural directives provides ability to tailor behavior to your application.
<p *ngIf="true">
Expression is true and ngIf is true.
This paragraph is in the DOM.
</p>
<p *ngIf="false">
Expression is false and ngIf is false.
This paragraph is not in the DOM.
</p>
Components :
Components are directives that their own templates, rather than relying on content provided from elsewhere. Components have access to all directive features, still have a host element, can still define input and output properties, and so on.But they also define their own content.
It can be easy to underestimate the importance of the template, but attribute and structural directives have limitations. Directives can do useful and powerful work, but they don’t have much insight into the elements they are applied to. Directives are most useful when they are general-purpose tools, such the ngModel
directive, which can be applied to any data model property and any form element, without regard to what the data or the element is being used for.
Components, by contrast, are closely tied to the contents of their templates. Components provide the data and logic that will be used by the data bindings that are applied to the HTML elements in the template, which provide the context used to evaluate data binding expressions and act as the glue between the directives and the rest of the application. Components are also a useful tool in allowing large Angular projects to be broken up into manageable chunks.
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
selector: 'app-hero-child',
template: `
<h3>{{hero.name}} says:</h3>
<p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
`
})
export class HeroChildComponent {
@Input() hero: Hero;
@Input('master') masterName: string;
}
참고URL : https://stackoverflow.com/questions/34613065/what-is-the-difference-between-component-and-directive
'Development Tip' 카테고리의 다른 글
Java에서 두 문자를 추가 한 결과는 int 또는 char입니까? (0) | 2020.10.23 |
---|---|
JObject에 JToken을 어떻게 추가합니까? (0) | 2020.10.23 |
Groovy에는 2 개의 맵을 병합하는 방법이 있습니까? (0) | 2020.10.23 |
matplotlib (동일한 단위 길이) : '동일한'종횡비 사용 z 축이 x 및 y-와 같지 않음 (0) | 2020.10.23 |
dplyr은 각각을 나열하지 않고 여러 변수를 요약 할 수 있습니까? (0) | 2020.10.23 |