목차
보간 표현식
템플릿 변수
값 바인딩, 이벤트 바인딩, 양방향 바인딩
내장 구조 지시문
내장 속성 지시문
Date
웹 프론트엔드 JS 튜토리얼 Angular의 템플릿 구문에 대한 자세한 설명

Angular의 템플릿 구문에 대한 자세한 설명

Apr 23, 2021 am 10:37 AM
angular

이 글에서는 Angular의 템플릿 구문에 대해 자세히 소개합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

Angular의 템플릿 구문에 대한 자세한 설명

추천 관련 튜토리얼: "angular tutorial"

보간 표현식

  • test-interpolation.comComponent.ts
@Component({
  selector: 'app-test-interpolation',
  templateUrl: './test-interpolation.component.html',
  styleUrls: ['./test-interpolation.component.css']
})
export class TestInterpolationComponent implements OnInit {

  title = '插值表达式';

  constructor() { }

  ngOnInit() {
  }

  getValue(): string {
    return '值';
  }
}
로그인 후 복사
  • test-interpolation.comComponent.html
rrre

템플릿 변수

  • test-template-variables.comComponent.ts
<div class="panel panel-primary">
  <div class="panel-heading">基插值语法</div>
  <div class="panel-body">
    <h3>
      欢迎来到 {{title}}!
    </h3>
    <h3>2+2 = {{2 + 2}}</h3>
    <h3>调用方法{{getValue()}}</h3>
  </div>
</div>
로그인 후 복사
  • test-template-variables.comComponent.html
@Component({
  selector: &#39;app-test-template-variables&#39;,
  templateUrl: &#39;./test-template-variables.component.html&#39;,
  styleUrls: [&#39;./test-template-variables.component.css&#39;]
})
export class TestTempRefVarComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  public saveValue(value: string): void {
    console.log(value);
  }
}
로그인 후 복사

값 바인딩, 이벤트 바인딩, 양방향 바인딩

값 바인딩 :[ ]

  • test-value-bind.comComponent.ts
<div class="panel panel-primary">
  <div class="panel-heading">模板变量</div>
  <div class="panel-body">
    <input #templateInput>
    <p>{{templateInput.value}}</p>
    <button class="btn btn-success" (click)="saveValue(templateInput.value)">局部变量</button>
  </div>
</div>
로그인 후 복사
  • test-value-bind.comComponent.html
@Component({
  selector: &#39;app-test-value-bind&#39;,
  templateUrl: &#39;./test-value-bind.component.html&#39;,
  styleUrls: [&#39;./test-value-bind.component.css&#39;]
})
export class TestValueBindComponent implements OnInit {

  public imgSrc = &#39;./assets/imgs/1.jpg&#39;;

  constructor() { }

  ngOnInit() {
  }
}
로그인 후 복사

이벤트 바인딩: ()

  • test-event-bind-Component.ts
<div class="panel panel-primary">
  <div class="panel-heading">单向值绑定</div>
  <div class="panel-body">
    <img [src]="imgSrc" />
  </div>
</div>
로그인 후 복사
  • test-event-bind.comComponent.html
@Component({
  selector: &#39;app-test-event-binding&#39;,
  templateUrl: &#39;./test-event-binding.component.html&#39;,
  styleUrls: [&#39;./test-event-binding.component.css&#39;]
})
export class TestEventBindingComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  public btnClick(event: any): void {
    console.log(event + &#39;测试事件绑定!&#39;);
  }
}
로그인 후 복사

양방향 바인딩: [()]

  • test-twoway-bind.comComponent.ts
<div class="panel panel-primary">
    <div class="panel-heading">事件绑定</div>
    <div class="panel-body">
        <button class="btn btn-success" (click)="btnClick($event)">点击按钮</button>
    </div>
</div>
로그인 후 복사
  • test- twoway- 바인딩.comComponent.html
@Component({
  selector: &#39;app-test-twoway-binding&#39;,
  templateUrl: &#39;./test-twoway-binding.component.html&#39;,
  styleUrls: [&#39;./test-twoway-binding.component.css&#39;]
})
export class TestTwowayBindingComponent implements OnInit {

  public fontSizePx = 14;

  constructor() { }

  ngOnInit() {
  }

}
로그인 후 복사
  • font-resizer.comComponent.ts
<div class="panel panel-primary">
  <div class="panel-heading">双向绑定</div>
  <div class="panel-body">
    <app-font-resizer [(size)]="fontSizePx"></app-font-resizer>
    <div [style.font-size.px]="fontSizePx">Resizable Text</div>
  </div>
</div>
로그인 후 복사
  • font-resizer.comComponent.html
@Component({
  selector: &#39;app-font-resizer&#39;,
  templateUrl: &#39;./font-resizer.component.html&#39;,
  styleUrls: [&#39;./font-resizer.component.css&#39;]
})
export class FontResizerComponent implements OnInit {

  @Input()
  size: number | string;

  @Output()
  sizeChange = new EventEmitter<number>();

  constructor() { }

  ngOnInit() {
  }

  decrement(): void {
    this.resize(-1);
  }

  increment(): void {
    this.resize(+1);
  }

  resize(delta: number) {
    this.size = Math.min(40, Math.max(8, +this.size + delta));
    this.sizeChange.emit(this.size);
  }
}
로그인 후 복사

내장 구조 지시문

*ngIf

  • 테스트 -ng-if.comComponent.ts
<div style="border: 2px solid #333">
  <p>这是子组件</p>
  <button (click)="decrement()" title="smaller">-</button>
  <button (click)="increment()" title="bigger">+</button>
  <label [style.font-size.px]="size">FontSize: {{size}}px</label>
</div>
로그인 후 복사
  • test-ng-if.comComponent.html
@Component({
  selector: &#39;app-test-ng-if&#39;,
  templateUrl: &#39;./test-ng-if.component.html&#39;,
  styleUrls: [&#39;./test-ng-if.component.css&#39;]
})
export class TestNgIfComponent implements OnInit {

  isShow = true;

  constructor() { }

  ngOnInit() {
  }
}
로그인 후 복사

*ngFor

  • test-ng-for.comComponent.ts
<div class="panel panel-primary">
  <div class="panel-heading">*ngIf的用法</div>
  <div class="panel-body">
    <p *ngIf="isShow" style="background-color:#ff3300">显示内容</p>
  </div>
</div>
로그인 후 복사
  • test- ng -for.comComponent.html
@Component({
  selector: &#39;app-test-ng-for&#39;,
  templateUrl: &#39;./test-ng-for.component.html&#39;,
  styleUrls: [&#39;./test-ng-for.component.css&#39;]
})
export class TestNgForComponent implements OnInit {

  races = [
    {name: &#39;star&#39;},
    {name: &#39;kevin&#39;},
    {name: &#39;kent&#39;}
  ];

  constructor() { }

  ngOnInit() {
  }

}
로그인 후 복사

ngSwitch

  • test-ng-switch.comComponent.ts
<div class="panel panel-primary">
  <div class="panel-heading">*ngFor用法</div>
  <div class="panel-body">
    <h3>名字列表</h3>
    <ul>
      <li *ngFor="let name of names;let i=index;">
       {{i}}-{{name.name}}
      </li>
    </ul>
  </div>
</div>
로그인 후 복사
  • test-ng-switch.comComponent.html
@Component({
  selector: &#39;app-test-ng-switch&#39;,
  templateUrl: &#39;./test-ng-switch.component.html&#39;,
  styleUrls: [&#39;./test-ng-switch.component.css&#39;]
})
export class TestNgSwitchComponent implements OnInit {

  status = 1;

  constructor() { }

  ngOnInit() {
  }

}
로그인 후 복사

내장 속성 지시문

HTML 속성과 DOM 속성의 관계

  • 몇몇 HTML 속성과 id와 같은 DOM 속성 사이에는 일대일 매핑 관계가 있습니다.
  • 일부 HTML 속성에는 해당 DOM이 없습니다.
  • textContent와 같은 일부 DOM 속성에는 해당 HTML 속성이 없습니다.
  • 이름이 동일하더라도 HTML 속성과 DOM 속성은 동일하지 않습니다. 속성은 초기 값을 지정하고 DOM 속성의 값은 현재 값을 나타냅니다. HTML 속성의 값은 변경할 수 없으며 DOM 속성의 값은 변경할 수 있습니다.
  • 템플릿 바인딩은 HTML 속성이 아닌 DOM 속성 및 이벤트를 통해 작동합니다.
참고:

보간 표현식과 속성 바인딩은 동일하며 보간 표현식은 DOM 속성 바인딩에 속합니다. ㅋㅋㅋ NgStyle

test-ng-style.comComponent.ts

<div class="panel panel-primary">
  <div class="panel-heading">ngSwitch用法</div>
  <div class="panel-body">
    <div [ngSwitch]="status">
      <p *ngSwitchCase="0">Good</p>
      <p *ngSwitchCase="1">Bad</p>
      <p *ngSwitchDefault>Exception</p>
    </div>
  </div>
</div>
로그인 후 복사

    test-ng-style.comComponent.html
  • @Component({
      selector: &#39;app-test-ng-class&#39;,
      templateUrl: &#39;./test-ng-class.component.html&#39;,
      styleUrls: [&#39;./test-ng-class.component.scss&#39;]
    })
    export class TestNgClassComponent implements OnInit {
      public currentClasses: {};
    
      public canSave = true;
      public isUnchanged = true;
      public isSpecial = true;
    
      constructor() { }
    
      ngOnInit() {
        this.currentClasses = {
          &#39;saveable&#39;: this.canSave,
          &#39;modified&#39;: this.isUnchanged,
          &#39;special&#39;: this.isSpecial
        };
      }
    }
    로그인 후 복사
    NgModel
    test-ng-model.comComponent.ts
  • <div class="panel panel-primary">
      <div class="panel-heading">NgClass用法</div>
      <div class="panel-body">
        <div [ngClass]="currentClasses">设置多个样式</div>
        <div [class.modified]=&#39;true&#39;></div>
      </div>
    </div>
    로그인 후 복사

test-ng-model.comComponent.html

.saveable {
    font-size: 18px;
}

.modified {
    font-weight: bold;
}

.special {
    background-color: #ff3300;
}
로그인 후 복사

    widget
    pipeline
Angular 내장 공통 파이프:

대문자 및 소문자

  • 대문자 문자를 대문자로 변환 사례 {
{'aaa' | 대문자}}
    소문자 문자를 소문자로 변환합니다. {
  • {'BBB' | 소문자}}

Date

{{ 생일 | 날짜: 'yyyy-MM-dd HH:mm ss'}}

    number
{

{ pi | number: '2.2-2'}} 2.2-2: 정수 2개와 소수점 이하 2자리를 유지한다는 의미입니다.
2-2: 최소 소수점 2자리, 최대 소수점 2자리를 나타냅니다.

test-pipe.comComponent.ts
@Component({
  selector: &#39;app-test-ng-style&#39;,
  templateUrl: &#39;./test-ng-style.component.html&#39;,
  styleUrls: [&#39;./test-ng-style.component.css&#39;]
})
export class TestNgStyleComponent implements OnInit {

  currentStyles: { };
  canSave = false;
  isUnchanged = false;
  isSpecial = false;

  constructor() { }

  ngOnInit() {
    this.currentStyles = {
      &#39;font-style&#39;: this.canSave ? &#39;italic&#39; : &#39;normal&#39;,
      &#39;font-weight&#39;: !this.isUnchanged ? &#39;bold&#39; : &#39;normal&#39;,
      &#39;font-size&#39;: this.isSpecial ? &#39;36px&#39; : &#39;12px&#39;
    };
  }

}
로그인 후 복사

test-pipe.comComponent.html

<div class="panel panel-primary">
  <div class="panel-heading">NgStyle用法</div>
  <div class="panel-body">
    <div [ngStyle]="currentStyles">
      用NgStyle批量修改内联样式!
    </div>
    <div [style.font-size]="isSpecial? &#39;36px&#39; : &#39;12px&#39;"></div>
  </div>
</div>
로그인 후 복사

null이 아닌 어설션
test-not-null-assert.comComponent.ts

@Component({
  selector: &#39;app-test-ng-model&#39;,
  templateUrl: &#39;./test-ng-model.component.html&#39;,
  styleUrls: [&#39;./test-ng-model.component.css&#39;]
})
export class TestNgModelComponent implements OnInit {

  name = &#39;kevin&#39;;

  constructor() { }

  ngOnInit() {
  }

}
로그인 후 복사

test-not-null-assert.comComponent.html

<div class="panel panel-primary">
    <div class="panel-heading">NgModel的用法</div>
    <div class="panel-body">
        <p class="text-danger">ngModel只能用在表单类的元素上面</p>
        <input type="text" name="name" [(ngModel)]="name">
    </div>
</div>
로그인 후 복사
더 많은 프로그래밍 관련 지식을 보려면
    프로그래밍 교육
  • 을 방문하세요! !

위 내용은 Angular의 템플릿 구문에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 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 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

Angular의 메타데이터와 데코레이터에 대해 이야기해 보겠습니다. Angular의 메타데이터와 데코레이터에 대해 이야기해 보겠습니다. Feb 28, 2022 am 11:10 AM

이 글은 Angular에 대한 학습을 ​​계속하고, Angular의 메타데이터와 데코레이터를 이해하고, 그 사용법을 간략하게 이해하는 데 도움이 되기를 바랍니다.

Ubuntu 24.04에 Angular를 설치하는 방법 Ubuntu 24.04에 Angular를 설치하는 방법 Mar 23, 2024 pm 12:20 PM

Angular.js는 동적 애플리케이션을 만들기 위해 자유롭게 액세스할 수 있는 JavaScript 플랫폼입니다. HTML 구문을 템플릿 언어로 확장하여 애플리케이션의 다양한 측면을 빠르고 명확하게 표현할 수 있습니다. Angular.js는 코드를 작성, 업데이트 및 테스트하는 데 도움이 되는 다양한 도구를 제공합니다. 또한 라우팅 및 양식 관리와 같은 많은 기능을 제공합니다. 이 가이드에서는 Ubuntu24에 Angular를 설치하는 방법에 대해 설명합니다. 먼저 Node.js를 설치해야 합니다. Node.js는 서버 측에서 JavaScript 코드를 실행할 수 있게 해주는 ChromeV8 엔진 기반의 JavaScript 실행 환경입니다. Ub에 있으려면

각도에서 monaco-editor를 사용하는 방법에 대한 간략한 분석 각도에서 monaco-editor를 사용하는 방법에 대한 간략한 분석 Oct 17, 2022 pm 08:04 PM

각도에서 모나코 편집기를 사용하는 방법은 무엇입니까? 다음 글은 최근 비즈니스에서 사용되는 Monaco-Editor의 활용 사례를 기록한 글입니다.

Angular의 서버 측 렌더링(SSR)을 탐색하는 기사 Angular의 서버 측 렌더링(SSR)을 탐색하는 기사 Dec 27, 2022 pm 07:24 PM

앵귤러 유니버셜(Angular Universal)을 아시나요? 웹사이트가 더 나은 SEO 지원을 제공하는 데 도움이 될 수 있습니다!

Angular + NG-ZORRO로 백엔드 시스템을 빠르게 개발 Angular + NG-ZORRO로 백엔드 시스템을 빠르게 개발 Apr 21, 2022 am 10:45 AM

이 기사는 Angular의 실제 경험을 공유하고 ng-zorro와 결합된 angualr을 사용하여 백엔드 시스템을 빠르게 개발하는 방법을 배우게 될 것입니다. 모든 사람에게 도움이 되기를 바랍니다.

프론트엔드 개발에 PHP와 Angular를 사용하는 방법 프론트엔드 개발에 PHP와 Angular를 사용하는 방법 May 11, 2023 pm 04:04 PM

인터넷의 급속한 발전과 함께 프론트엔드 개발 기술도 지속적으로 개선되고 반복되고 있습니다. PHP와 Angular는 프런트엔드 개발에 널리 사용되는 두 가지 기술입니다. PHP는 양식 처리, 동적 페이지 생성, 액세스 권한 관리와 같은 작업을 처리할 수 있는 서버측 스크립팅 언어입니다. Angular는 단일 페이지 애플리케이션을 개발하고 구성 요소화된 웹 애플리케이션을 구축하는 데 사용할 수 있는 JavaScript 프레임워크입니다. 이 기사에서는 프론트엔드 개발에 PHP와 Angular를 사용하는 방법과 이들을 결합하는 방법을 소개합니다.

각도 학습 상태 관리자 NgRx에 대한 자세한 설명 각도 학습 상태 관리자 NgRx에 대한 자세한 설명 May 25, 2022 am 11:01 AM

이 글은 Angular의 상태 관리자 NgRx에 대한 심층적인 이해를 제공하고 NgRx 사용 방법을 소개하는 글이 될 것입니다.

Angular 및 Node를 사용한 토큰 기반 인증 Angular 및 Node를 사용한 토큰 기반 인증 Sep 01, 2023 pm 02:01 PM

인증은 모든 웹 애플리케이션에서 가장 중요한 부분 중 하나입니다. 이 튜토리얼에서는 토큰 기반 인증 시스템과 기존 로그인 시스템과의 차이점에 대해 설명합니다. 이 튜토리얼이 끝나면 Angular와 Node.js로 작성된 완벽하게 작동하는 데모를 볼 수 있습니다. 기존 인증 시스템 토큰 기반 인증 시스템으로 넘어가기 전에 기존 인증 시스템을 살펴보겠습니다. 사용자는 로그인 양식에 사용자 이름과 비밀번호를 입력하고 로그인을 클릭합니다. 요청한 후 데이터베이스를 쿼리하여 백엔드에서 사용자를 인증합니다. 요청이 유효하면 데이터베이스에서 얻은 사용자 정보를 이용하여 세션을 생성하고, 세션 정보를 응답 헤더에 반환하여 브라우저에 세션 ID를 저장한다. 다음과 같은 애플리케이션에 대한 액세스를 제공합니다.

See all articles