찾다
웹 프론트엔드JS 튜토리얼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 id="nbsp-nbsp-nbsp-nbsp">2+2 = {{2 + 2}}</h3>
    <h3 id="调用方法-getValue">调用方法{{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" / alt="Angular의 템플릿 구문에 대한 자세한 설명" >
  </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>
    <div>事件绑定</div>
    <div>
        <button>点击按钮</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 id="名字列表">名字列表</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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
이 기사는 csdn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
JavaScript 및 웹 : 핵심 기능 및 사용 사례JavaScript 및 웹 : 핵심 기능 및 사용 사례Apr 18, 2025 am 12:19 AM

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

JavaScript 엔진 이해 : 구현 세부 사항JavaScript 엔진 이해 : 구현 세부 사항Apr 17, 2025 am 12:05 AM

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python vs. JavaScript : 학습 곡선 및 사용 편의성Python vs. JavaScript : 학습 곡선 및 사용 편의성Apr 16, 2025 am 12:12 AM

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

Python vs. JavaScript : 커뮤니티, 라이브러리 및 리소스Python vs. JavaScript : 커뮤니티, 라이브러리 및 리소스Apr 15, 2025 am 12:16 AM

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

C/C에서 JavaScript까지 : 모든 것이 어떻게 작동하는지C/C에서 JavaScript까지 : 모든 것이 어떻게 작동하는지Apr 14, 2025 am 12:05 AM

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

JavaScript 엔진 : 구현 비교JavaScript 엔진 : 구현 비교Apr 13, 2025 am 12:05 AM

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

브라우저 너머 : 실제 세계의 JavaScript브라우저 너머 : 실제 세계의 JavaScriptApr 12, 2025 am 12:06 AM

실제 세계에서 JavaScript의 응용 프로그램에는 서버 측 프로그래밍, 모바일 애플리케이션 개발 및 사물 인터넷 제어가 포함됩니다. 1. 서버 측 프로그래밍은 Node.js를 통해 실현되며 동시 요청 처리에 적합합니다. 2. 모바일 애플리케이션 개발은 재교육을 통해 수행되며 크로스 플랫폼 배포를 지원합니다. 3. Johnny-Five 라이브러리를 통한 IoT 장치 제어에 사용되며 하드웨어 상호 작용에 적합합니다.

Next.js (백엔드 통합)로 멀티 테넌트 SAAS 애플리케이션 구축Next.js (백엔드 통합)로 멀티 테넌트 SAAS 애플리케이션 구축Apr 11, 2025 am 08:23 AM

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.

See all articles

핫 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

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경