컴포넌트 템플릿에서 요소를 어떻게 선택할 수 있습니까?
구성 요소 템플릿에 정의 된 요소를 얻는 방법을 아는 사람이 있습니까? 폴리머는 $
and로 정말 쉬워집니다 $$
.
Angular에서 어떻게 진행해야하는지 궁금했습니다.
튜토리얼에서 예제를 보자.
import {Component} from '@angular/core'
@Component({
selector:'display'
template:`
<input #myname(input)="updateName(myname.value)"/>
<p>My name : {{myName}}</p>
`
})
export class DisplayComponent {
myName: string = "Aman";
updateName(input: String) {
this.myName = input;
}
}
클래스 정의 내에서 p
또는 input
요소 에 대한 참조를 잡으려면 어떻게해야 합니까?
거기에서 주입 ElementRef
하거나 사용 querySelector
하거나 유사한 대신에 , 선언적 방법을 사용하여 뷰의 요소에 직접 액세스 할 수 있습니다.
<input #myname>
@ViewChild('myname') input;
요소
ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}
- @ViewChild () 는 지시문 또는 구성 요소 유형을 매개 변수 또는 템플리트 변수의 이름 (문자열)으로 지원합니다.
- @ViewChildren () 은 또한 이름 목록을 쉼표로 구분 된 목록으로 지원합니다 (현재 공백은 허용되지 않음
@ViewChildren('var1,var2,var3')
). - @ContentChild () 와 @ContentChildren () 은 동일하지만 가벼운 DOM (
<ng-content>
투사 요소)에서 작동합니다.
자손
@ContentChildren()
자손을 쿼리 할 수있는 유일한 사람입니다.
@ContentChildren(SomeTypeOrVarName, {descendants: true}) someField;
{descendants: true}
기본값이어야하지만 2.0.0 최종 버전이 아니며
버그로 간주
됩니다. 2.0.1에서 수정되었습니다.
읽다
구성 요소 및 지시문이있는 경우 read
매개 변수를 통해 리턴 할 인스턴스를 지정할 수 있습니다.
예를 들어 ViewContainerRef
기본값 대신 동적으로 생성 된 구성 요소에 필요한ElementRef
@ViewChild('myname', { read: ViewContainerRef }) target;
구독 변경
뷰 하위 ngAfterViewInit()
는 호출 될 때만 설정 되고 컨텐츠 하위는 호출 될 때만 설정되지만 ngAfterContentInit()
쿼리 결과의 변경을 구독하려면 다음에서 수행해야합니다.ngOnInit()
https://github.com/angular/angular/issues/9689#issuecomment-229247134
@ViewChildren(SomeType) viewChildren;
@ContentChildren(SomeType) contentChildren;
ngOnInit() {
this.viewChildren.changes.subscribe(changes => console.log(changes));
this.contentChildren.changes.subscribe(changes => console.log(changes));
}
직접적인 DOM 액세스
DOM 요소 만 쿼리 할 수 있지만 컴포넌트 또는 지시문 인스턴스는 조회 할 수 없습니다.
export class MyComponent {
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
var div = this.elRef.nativeElement.querySelector('div');
console.log(div);
}
// for transcluded content
ngAfterContentInit() {
var div = this.elRef.nativeElement.querySelector('div');
console.log(div);
}
}
임의의 투영 된 컨텐츠를 얻는다
변환 된 컨텐츠 액세스를 참조하십시오.
ElementRef
컴포넌트의 생성자에 DOM 요소를 삽입 하여 DOM 요소에 대한 핸들을 얻을 수 있습니다 .
constructor(myElement: ElementRef) { ... }
문서 : https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html
import { Component, ElementRef, OnInit } from '@angular/core';
@Component({
selector:'display',
template:`
<input (input)="updateName($event.target.value)">
<p> My name : {{ myName }}</p>
`
})
class DisplayComponent implements OnInit {
constructor(public element: ElementRef) {
this.element.nativeElement // <- your direct element reference
}
ngOnInit() {
var el = this.element.nativeElement;
console.log(el);
}
updateName(value) {
// ...
}
}
최신 버전으로 작동하도록 업데이트 된 예
기본 요소에 대한 자세한 내용은 여기를 참조하십시오.
Angular 4+ : renderer.selectRootElement
CSS 선택기와 함께 사용 하여 요소에 액세스합니다.
처음에는 이메일 입력을 표시하는 양식이 있습니다. 이메일을 입력하면 양식이 확장되어 프로젝트와 관련된 정보를 계속 추가 할 수 있습니다. 그러나 기존 고객 이 아닌 경우 양식에 프로젝트 정보 섹션 위에 주소 섹션이 포함됩니다.
현재 데이터 입력 부분이 구성 요소로 분리되지 않았으므로 섹션은 * ngIf 지시문으로 관리됩니다. 기존 클라이언트 인 경우 프로젝트 노트 필드에 초점을 설정하고 새로운 클라이언트 인 경우 이름 필드에 초점을 설정해야합니다.
나는 성공하지 않고 솔루션을 시도했다. 그러나에 업데이트 3 이 대답은 나에게 최종 솔루션의 절반을했다. 나머지 절반은 이 스레드 에서 MatteoNY의 응답에서 비롯되었습니다 . 결과는 다음과 같습니다.
import { NgZone, Renderer } from '@angular/core';
constructor(private ngZone: NgZone, private renderer: Renderer) {}
setFocus(selector: string): void {
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
this.renderer.selectRootElement(selector).focus();
}, 0);
});
}
submitEmail(email: string): void {
// Verify existence of customer
...
if (this.newCustomer) {
this.setFocus('#firstname');
} else {
this.setFocus('#description');
}
}
내가하고있는 유일한 일은 요소에 초점을 맞추는 것이므로 변경 감지에 신경 쓸 필요가 없으므로 실제로 renderer.selectRootElement
Angular 외부로 전화를 걸 수 있습니다 . 새 섹션에 렌더링 시간을 제공해야하므로 요소 선택을 시도하기 전에 렌더링 스레드 시간을 따라 잡을 수 있도록 요소 섹션이 시간 초과로 래핑됩니다. 모든 설정이 완료되면 기본 CSS 선택기를 사용하여 요소를 간단히 호출 할 수 있습니다.
이 예제는 주로 포커스 이벤트를 다루었지만 다른 상황에서는 사용할 수 없다는 것이 어렵습니다.
*ngIf
또는의 내부에서 구성 요소 인스턴스를 가져 오려는 *ngSwitchCase
경우이 트릭을 수행 할 수 있습니다.
init
지시문을 작성하십시오 .
import {
Directive,
EventEmitter,
Output,
OnInit,
ElementRef
} from '@angular/core';
@Directive({
selector: '[init]'
})
export class InitDirective implements OnInit {
constructor(private ref: ElementRef) {}
@Output() init: EventEmitter<ElementRef> = new EventEmitter<ElementRef>();
ngOnInit() {
this.init.emit(this.ref);
}
}
다음과 같은 이름으로 구성 요소를 내 보냅니다. myComponent
@Component({
selector: 'wm-my-component',
templateUrl: 'my-component.component.html',
styleUrls: ['my-component.component.css'],
exportAs: 'myComponent'
})
export class MyComponent { ... }
이 템플릿을 사용하여 ElementRef
AND MyComponent
인스턴스 를 가져옵니다.
<div [ngSwitch]="type">
<wm-my-component
#myComponent="myComponent"
*ngSwitchCase="Type.MyType"
(init)="init($event, myComponent)">
</wm-my-component>
</div>
TypeScript에서이 코드를 사용하십시오.
init(myComponentRef: ElementRef, myComponent: MyComponent) {
}
에서 ViewChild
데코레이터를 가져옵니다 @angular/core
.
HTML 코드 :
<form #f="ngForm">
...
...
</form>
TS 코드 :
import { ViewChild } from '@angular/core';
class TemplateFormComponent {
@ViewChild('f') myForm: any;
.
.
.
}
이제 'myForm'객체를 사용하여 클래스 내의 모든 요소에 액세스 할 수 있습니다.
*/
import {Component,ViewChild} from '@angular/core' /*Import View Child*/
@Component({
selector:'display'
template:`
<input #myname (input) = "updateName(myname.value)"/>
<p> My name : {{myName}}</p>
`
})
export class DisplayComponent{
@ViewChild('myname')inputTxt:ElementRef; /*create a view child*/
myName: string;
updateName: Function;
constructor(){
this.myName = "Aman";
this.updateName = function(input: String){
this.inputTxt.nativeElement.value=this.myName;
/*assign to it the value*/
};
}
}
참고 :이 각도 6 적용으로 이상하지 않습니다ElementRef
되었다ElementRef<T>
과T
유형을 나타내는nativeElement
.
난 당신이 사용하는 경우 있음을 추가하고 싶은 ElementRef
모든 답변에서 권장하는대로, 당신은 즉시 문제가 발생합니다 ElementRef
끔찍한 유형 선언이있다을 보이는 등
export declare class ElementRef {
nativeElement: any;
}
이것은 nativeElement가 브라우저 환경에서 바보입니다 HTMLElement
.
이 문제를 해결하려면 다음 기술을 사용할 수 있습니다
import {Inject, ElementRef as ErrorProneElementRef} from '@angular/core';
interface ElementRef {
nativeElement: HTMLElement;
}
@Component({...}) export class MyComponent {
constructor(@Inject(ErrorProneElementRef) readonly elementRef: ElementRef) { }
}
즉시 다음 형제를 얻으려면 이것을 사용하십시오.
event.source._elementRef.nativeElement.nextElementSibling
목록에서 대상 요소를 선택하십시오. 동일한 요소 목록에서 특정 요소를 쉽게 선택할 수 있습니다.
구성 요소 코드 :
export class AppComponent {
title = 'app';
listEvents = [
{'name':'item1', 'class': ''}, {'name':'item2', 'class': ''},
{'name':'item3', 'class': ''}, {'name':'item4', 'class': ''}
];
selectElement(item: string, value: number) {
console.log("item="+item+" value="+value);
if(this.listEvents[value].class == "") {
this.listEvents[value].class='selected';
} else {
this.listEvents[value].class= '';
}
}
}
html 코드 :
<ul *ngFor="let event of listEvents; let i = index">
<li (click)="selectElement(event.name, i)" [class]="event.class">
{{ event.name }}
</li>
CSS 코드 :
.selected {
color: red;
background:blue;
}
참고 URL : https://stackoverflow.com/questions/32693061/how-can-i-select-an-element-in-a-component-template
'Programming' 카테고리의 다른 글
NSString에 퍼센트 부호를 추가하는 방법 (0) | 2020.02.16 |
---|---|
UTF-8과 유니 코드의 차이점은 무엇입니까? (0) | 2020.02.16 |
가장자리가 아닌 div 내부에 테두리 배치 (0) | 2020.02.16 |
C #에서 URL에 대한 쿼리 문자열을 작성하는 방법은 무엇입니까? (0) | 2020.02.16 |
속성의 값으로 인덱스를 갖는 ngFor (0) | 2020.02.16 |