周斌生 發表於 2023-9-22 18:45:00

Angular入门

<h4 id="构建项目">构建项目</h4>
<pre><code>// 安装angular-cli
npm install -g @angular/cli
// 创建项目
ng new angular01
// 是否安装路由
// 选择(css/less/sass)
// 进入项目
cd angular01
// 安装依赖
npm install
// 启动并打开浏览器
ng serve -o
</code></pre>
<ul>
<li>导入vscode后,安装angular提示的插件</li>
</ul>
<h4 id="目录结构">目录结构</h4>
<ul>
<li>第一层文件</li>
</ul>
<pre><code>node_modules                第三方依赖包存放目录
e2e                                端到端的测试目录用来做自动测试的
src                                   应用源代码目录
.angular-cli.json   Angular命令行工具的配置文件。后期可能会去修改它,引一些其他的第三方的包比如jquery等
karma.conf.js                karma是单元测试的执行器,karma.conf.js是karma的配置文件
package.json                   这是一个标准的npm工具的配置文件,这个文件里面列出了该应用程序所使用的第三方依赖包。实际上我们在新建项目的时候,等了半天就是在下载第三方依赖包。下载完成后会放在node_modules这个目录中,后期我们可能会修改这个文件。
protractor.conf.js也是一个做自动化测试的配置文件
README.md         说明文件
tslint.json               是tslint的配置文件,用来定义TypeScript代码质量检查的规则,不用管它
</code></pre>
<ul>
<li>src目录</li>
</ul>
<pre><code>app目录                                包含应用的组件和模块,我们要写的代码都在这个目录
assets目录                资源目录,存储静态资源的比如图片
environments目录           环境配置。Angular是支持多环境开发的,我们可以在不同的环境下(开发环境,测试环境,生产环境)共用一套代码,主要用来配置环境的
index.html                整个应用的根html,程序启动就是访问这个页面
main.ts                            整个项目的入口点,Angular通过这个文件来启动项目
polyfills.ts                   主要是用来导入一些必要库,为了让Angular能正常运行在老版本下
styles.css                   主要是放一些全局的样式
tsconfig.app.json        TypeScript编译器的配置,添加第三方依赖的时候会修改这个文件
tsconfig.spec.json        不用管
test.ts                            也是自动化测试用的
typings.d.ts      不用管
</code></pre>
<ul>
<li>app目录</li>
</ul>
<pre><code>src\app\app.component.html      // 根组件
src\app\app.component.less      // 根组件
src\app\app.component.ts      // 根组件
src\app\app.module.ts          // 根模块
</code></pre>
<ul>
<li>根模块app.module.ts</li>
</ul>
<pre><code>// angular核心模块
import { NgModule } from '@angular/core';
// 浏览器解析模块
import { BrowserModule } from '@angular/platform-browser';
// 路由模块
import { AppRoutingModule } from './app-routing.module';
// 导入app目录下的三个根组件:app.component.html,app.component.less,app.component.ts
import { AppComponent } from './app.component';
@NgModule({
declarations: [
    AppComponent      // 将上面导入的根组件注册为自己的组件
],
imports: [         // 配置依赖的其他模块
    BrowserModule,      // 类似于导入挂载
    AppRoutingModule
],
providers: [],
bootstrap:       // 指定根组件来启动应用
})
export class AppModule { }      // 暴露当前接口,根模块可不用暴露
</code></pre>
<ul>
<li>根组件app.component.ts</li>
</ul>
<pre><code>// 导入angular的核心
import { Component } from '@angular/core';
@Component({
selector: 'app-root',   // 导入该组件的名称
templateUrl: './app.component.html',    // 导入根组件html
styleUrls: ['./app.component.less']   // 导入根组件less
})
export class AppComponent {   // 定义根组件的属性
title = 'angular01';
}
</code></pre>
<h4 id="新建子组件">新建子组件</h4>
<ul>
<li>初始化项目:删除app.component.html中的默认代码</li>
</ul>
<pre><code>&lt;style&gt;
&lt;/style&gt;

&lt;div&gt;
这是根组件
&lt;/div&gt;

&lt;router-outlet&gt;&lt;/router-outlet&gt;
</code></pre>
<ul>
<li>新建子组件</li>
</ul>
<pre><code>// 提示
ng g
// 在app/components/路径下新建组件news
ng g component components/news

// 之后就会在components路径下生成news文件夹,整个文件夹都是news组件
// 在根模块app.module.ts中会自动引入news组件
import { NewsComponent } from './components/news/news.component';
@NgModule({
declarations: [
    NewsComponent      // 将上面导入的根组件注册为自己的组件
]
})

// 在子组件news.component.ts中
@Component({
selector: 'app-news',    // 当前组件名称
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})

// 在根组件中使用news组件
&lt;app-news&gt;&lt;/app-news&gt;
</code></pre>
<h4 id="模板合成">模板合成</h4>
<ul>
<li>数据绑定</li>
</ul>
<pre><code class="language-ts">// 在news.component.ts中绑定一个title
export class NewsComponent implements OnInit {

// 修饰符类型:public、private、protected
public title: string="我是一个新闻组件";

// 生成一个对象
public userinfo: Object ={
    name:"张山",
    age:20
};

// 在构造函数中传入属性的值
constructor() {
    this.title="这是改变后的值";
}
}

// 在news.component.html中使用
&lt;span&gt;{{title}}&lt;/span&gt;
&lt;span&gt;{{userinfo}}&lt;/span&gt;
</code></pre>
<ul>
<li>属性绑定</li>
</ul>
<pre><code class="language-html">// news.component.ts中
export class NewsComponent implements OnInit {

public baidu: string="www.baidu.com";
}

// news.component.html中
&lt;h2&gt;属性绑定&lt;/h2&gt;
&lt;p title="这是title"&gt;baidu_0&lt;/p&gt;
&lt;p ="baidu"&gt;baidu_1&lt;/p&gt;&lt;br&gt;
&lt;a ="baidu"&gt;baidu_2&lt;/a&gt;&lt;br&gt;
</code></pre>
<ul>
<li>html绑定</li>
</ul>
<pre><code class="language-html">// news.component.ts中
export class NewsComponent implements OnInit {

// html绑定
public content: string="&lt;h2&gt;这是一段文本!!&lt;/h2&gt;"
public content2:string=`
    &lt;span&gt;title&lt;/span&gt;
    &lt;p&gt;p2&lt;/p&gt;
`
}

// news.component.html中
&lt;h2&gt;绑定html&lt;/h2&gt;
&lt;p&gt;{{content}}&lt;/p&gt;
&lt;p ="content"&gt;&lt;/p&gt;
&lt;p ="content2"&gt;&lt;/p&gt;
</code></pre>
<ul>
<li>简单运算</li>
</ul>
<pre><code class="language-html">&lt;h2&gt;简单运算&lt;/h2&gt;
&lt;p&gt;333+555={{333+555}}&lt;/p&gt;
</code></pre>
<ul>
<li>数据循环</li>
</ul>
<pre><code class="language-html">export class NewsComponent implements OnInit {
// 数组循环
public arr=["ass", "dsdsa", "asdf"];
public list: string[]=["asdfasd", "asdfasd", "asdfasdf", "adsfasd"];
public items:Array&lt;string&gt;=["asd", "asdf", "1324"];
public userList:object[]=[{username:"user", password: "123456"},{username: "user2", password: "1234567"}]
}

&lt;h2&gt;数据循环&lt;/h2&gt;
&lt;ul&gt;
    &lt;li *ngFor="let item of arr"&gt;
      {{item}}
    &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;-------&lt;/p&gt;
&lt;ul&gt;
    &lt;li *ngFor="let item of list"&gt;
      {{item}}
    &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;-------&lt;/p&gt;
&lt;ul&gt;
    &lt;li *ngFor="let item of items"&gt;
      {{item}}
    &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;-------&lt;/p&gt;
&lt;ul&gt;&lt;/ul&gt;
&lt;li *ngFor="let item of userList"&gt;
    {{item.username}}
&lt;/li&gt;
</code></pre>
<h4 id="组件合成">组件合成</h4>
<ul>
<li>新建子组件home,以下操作在home组件中完成</li>
<li>引入图片</li>
</ul>
<pre><code class="language-ts">// ts组件中指定图片地址
public picUrl:string="https://tse4-mm.cn.bing.net/th/id/OIP-C.uPx-FbZ4nf2U05kCoJ7_1QHaE8?w=299&amp;h=197&amp;c=7&amp;r=0&amp;o=5&amp;dpr=1.24&amp;pid=1.7";

// html组件中
&lt;span&gt;&lt;img src="assets/images/OIP-C.jpg"&gt;&lt;/span&gt;&lt;br&gt;
&lt;p&gt;引入图片方式二&lt;/p&gt;
&lt;img ="picUrl"&gt;
</code></pre>
<ul>
<li>循环数据时,显示索引</li>
</ul>
<pre><code class="language-ts">// ts组件中指定数组
public list: any[]=[
    {"title":'新闻一'},{"title":'新闻二'},{"title":'新闻三'}
]

// html组件中
&lt;ul&gt;
&lt;li *ngFor="let item of list; let key=index"&gt;
    {{key}}----{{item.title}}
&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<ul>
<li>ngif条件判断</li>
</ul>
<pre><code class="language-ts">public flag:boolean=false;

// html组件中
&lt;div *ngIf="flag"&gt;
&lt;img src="assets/images/OIP-C.jpg"&gt;
&lt;/div&gt;
&lt;div *ngIf="!flag"&gt;
&lt;img ="picUrl"&gt;
&lt;/div&gt;
</code></pre>
<ul>
<li>ngSwitch条件判断</li>
</ul>
<pre><code class="language-ts">// ts组件中
public orderStatus:number=1;

// html组件中
&lt;span ="orderStatus"&gt;
&lt;p *ngSwitchCase="1"&gt;已经支付&lt;/p&gt;
&lt;p *ngSwitchCase="2"&gt;未支付&lt;/p&gt;
&lt;p *ngSwitchCase="3"&gt;已收货&lt;/p&gt;
&lt;p *ngSwitchCase="4"&gt;为收货&lt;/p&gt;
&lt;/span&gt;
</code></pre>
<ul>
<li>ngclass样式绑定</li>
</ul>
<pre><code class="language-ts">// ts组件中
public flag:boolean=false;

// less组件中
.red{
    color: red;
}
.blue{
    color: blue;
}
.yellow{
    color: yellow;
}

// html组件中
&lt;!-- 类名class1为true表示使用该样式 --&gt;
&lt;div ="{'class1':true, 'class2':false}"&gt;&lt;/div&gt;
&lt;!-- flag为home.component.ts中定义的boolean类型 --&gt;
&lt;div ="{'class3':flag, 'class4':!flag}"&gt;&lt;/div&gt;
&lt;ul&gt;
&lt;li *ngFor="let item of list; let key=index;" ="{'red': key==1, 'blue': key==2}"&gt;
    {{key}}----{{item.title}}
&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<ul>
<li>样式绑定ngStyle</li>
</ul>
<pre><code class="language-ts">// ts 组件中
public attr: string='red';
// less 组件中
.red{
    color: red;
}
// html 组件中
&lt;p ="{'color':'red'}"&gt;这是一段文本&lt;/p&gt;
&lt;p ="{'color':attr}"&gt;这是一段文本2&lt;/p&gt;
</code></pre>
<ul>
<li>管道:转换格式</li>
</ul>
<pre><code class="language-ts">// ts组件中
public today: any=new Date();
// html 组件中
&lt;span&gt;未转换 -&gt; &lt;/span&gt;{{today}}
&lt;br&gt;
&lt;span&gt;转换后 -&gt; &lt;/span&gt;{{today | date:'yyyy-mm-dd HH-mm-ss'}}
</code></pre>
<ul>
<li>点击事件</li>
</ul>
<pre><code class="language-ts">// ts组件中
// 事件
run(){
    alert("hello!!");
}
// 获取
getData(){
    alert(this.picUrl);
}

public title: string="asdf";
// 设置数据
setData(){
    this.title="sadfasdf"
}

// 点击获取事件对象
runEvent(e){
    var dom: any =e.target;
    dom.style.color='red';
    dom.style.height='200px';
}
</code></pre>
<pre><code class="language-html">&lt;button (click)="run()"&gt;点击1&lt;/button&gt;
&lt;br&gt;
&lt;!-- 点击时获取数据 --&gt;
&lt;button (click)="getData()"&gt;点击1&lt;/button&gt;
&lt;br&gt;
&lt;!-- 点击时改变数据 --&gt;
data:{{title}}
&lt;button (click)="setData()"&gt;点击2&lt;/button&gt;
&lt;br&gt;
&lt;br&gt;
&lt;button (click)="runEvent($event)"&gt;点击获取事件对象&lt;/button&gt;
</code></pre>
<ul>
<li>键盘事件</li>
</ul>
<pre><code>// ts组件中
keyDown(e){
    if(e.keyCode==13){
      console.log("按了回车")
    }else{
      console.log(e.target.value)
    }
}
// 键盘松开事件
keyUp(e){
    if(e.keyCode==13){
      console.log(e.target.value)
      console.log("按了回车")
    }
}

// html组件中
键盘按下&lt;input type="text" (keydown)="keyDown($event)"/&gt;
键盘松开&lt;input type="text" (keyup)="keyUp($event)"&gt;
</code></pre>
<ul>
<li>报错</li>
</ul>
<pre><code>Error: src/app/components/home/home.component.ts:50:11 - error TS7006: Parameter 'e' implicitly has an 'any' type.   

50   keyDown(e){
</code></pre>
<ul>
<li>
<p>解决方案</p>
</li>
<li>
<p>双向数据绑定需在根组件中引入FormsModule</p>
</li>
</ul>
<pre><code class="language-ts">// app.module.ts中导入form组件
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [         // 配置依赖的其他模块
    FormsModule
],
})

// ts组件中
public keywords: any;

// html组件中
&lt;input type="text" [(ngModel)]='keywords'/&gt;
&lt;br&gt;{{keywords}}
</code></pre>
<ul>
<li>报错</li>
</ul>
<pre><code>Property 'keywords' does not exist on type 'HomeComponent'.

76 &lt;br&gt;{{keywords}}
</code></pre>
<ul>
<li>错误原因:ts中keywords没有指定类型</li>
</ul>
<h4 id="表单双向绑定">表单双向绑定</h4>
<ul>
<li>新建子组件form</li>
<li>ts组件</li>
</ul>
<pre><code class="language-ts">export class FormComponent implements OnInit {
// 表单数据绑定
public people: any = {
    username: '',
    sex: '1',
    cityList: ['shanghai', 'beijing', 'chongqing'],
    city: 'shanghai',
    hobby: [
      {title: 'lanqiu', checked: false},{title: 'cang', checked: false},{title: 'tiao', checked: false}
    ],
    mark: ''
}
}
</code></pre>
<ul>
<li>html组件</li>
</ul>
<pre><code class="language-html">&lt;p&gt;文本框双向绑定&lt;/p&gt;
&lt;input type="text" [(ngModel)]="people.username"&gt;
&lt;br&gt;{{people.username}}
&lt;p&gt;单选框双向绑定&lt;/p&gt;
&lt;input type="radio" value="1" [(ngModel)]="people.sex"&gt;
&lt;input type="radio" value="2" [(ngModel)]="people.sex"&gt;&lt;br&gt;
&lt;br&gt;{{people.sex}}
&lt;p&gt;下拉列表双向绑定&lt;/p&gt;
&lt;select [(ngModel)]="people.city"&gt;
    &lt;option *ngFor="let item of people.cityList" ="item"&gt;{{item}}&lt;/option&gt;
&lt;/select&gt;
&lt;br&gt;{{people.city}}
&lt;p&gt;多选框双向数据绑定&lt;/p&gt;
&lt;span *ngFor="let item of people.hobby, let key=index"&gt;
    &lt;input type="checkbox" id="check+'key'" [(ngModel)]="item.checked"&gt;{{item.title}}--{{item.checked}}
&lt;/span&gt;
&lt;br&gt;
&lt;p&gt;文本域双向数据绑定&lt;/p&gt;
&lt;textarea [(ngModel)]="people.mark"&gt;&lt;/textarea&gt;
&lt;br&gt;{{people.mark}}
</code></pre>
<h4 id="搜索框历史功能">搜索框历史功能</h4>
<ul>
<li>新建子组件search</li>
<li>html组件</li>
</ul>
<pre><code class="language-html">&lt;div class="search"&gt;
    &lt;!-- 文本框双向绑定 --&gt;
    &lt;input type="text" [(ngModel)]="keyword" placeholder="Search"&gt;
    &lt;!-- 点击按钮添加到历史记录 --&gt;
    &lt;button type="button" (click)="doSearch()"&gt;search&lt;/button&gt;
    &lt;br&gt;
    &lt;div class="historyList"&gt;
      &lt;!-- 遍历循环历史记录,点击删除事件 --&gt;
      &lt;li *ngFor="let item of historyList; let key=index;"&gt;
            {{item}}&lt;span (click)="deleteHistory(key)" class="del"&gt;X&lt;/span&gt;
      &lt;/li&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<ul>
<li>ts组件</li>
</ul>
<pre><code class="language-ts">// 与搜索框双向绑定
public keyword: string;
// 历史记录的数组
public historyList: any[] = [];
// 判断历史记录中是否存在,添加到历史记录
doSearch(){
    if(this.historyList.indexOf(this.keyword)==-1){
      this.historyList.push(this.keyword);
    }
    this.keyword='';
}
// 删除历史记录
deleteHistory(key){
    //alert(key);
    this.historyList.splice(key, 1);
}
</code></pre>
<h4 id="事项清单">事项清单</h4>
<ul>
<li>新建子组件todolist</li>
<li>html组件</li>
</ul>
<pre><code class="language-html">&lt;div class="todolist"&gt;
    &lt;!-- 文本框双向绑定,键盘事件添加历史记录 --&gt;
    &lt;input type="text" placeholder="Search" [(ngModel)]="keyword" (keyup)="doAdd($event)"&gt;
    &lt;hr&gt;
    &lt;div class="historyList"&gt;
      &lt;p&gt;待办事项&lt;/p&gt;
      &lt;div class="history"&gt;&lt;/div&gt;
            &lt;!-- 遍历历史记录,hidden表示status=0时显示 --&gt;
            &lt;div class="his"*ngFor="let item of todolist; let key=index;" ="item.status==1"&gt;
                &lt;!-- 双向绑定状态status --&gt;
                &lt;input type="checkbox" [(ngModel)]="item.status" class="inp"&gt;
                {{item.title}}
                &lt;span class="del" (click)="delete(key)"&gt;x&lt;/span&gt;
            &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="todos"&gt;
      &lt;p&gt;已完成事项&lt;/p&gt;
      &lt;div class="todo2"&gt;
            &lt;!-- 遍历历史记录数组,hidden表示status为1时显示;删除记录的方法 --&gt;
            &lt;div class="todo" *ngFor="let item of todolist; let key=index;" ="item.status==0"&gt;
                &lt;!-- 双向绑定单条历史记录的状态 --&gt;
                &lt;input type="checkbox" [(ngModel)]="item.status" class="inp"&gt;
                {{item.title}}
                &lt;span class="del" (click)="delete2(key)"&gt;x&lt;/span&gt;
            &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<ul>
<li>ts组件</li>
</ul>
<pre><code class="language-ts">export class TodolistComponent implements OnInit {
// 双向绑定搜索框
public keyword: string;
// 默认的历史记录
public todolist: any[] = [{title: 'vuejs', status: 0}];
// 添加历史记录的方法
doAdd(e){
    if(e.keyCode==13){
      this.todolist.push({title: this.keyword, status: 0});
      this.keyword='';
    }
}
// 删除历史记录的方法
delete(key){
    this.todolist.splice(key,1);
}
// 删除历史记录的方法
delete2(key){
    this.todolist.splice(key,1);
}
}
</code></pre>
<h4 id="angular服务">angular服务</h4>
<ul>
<li>angular是基于组件化的开发,一个组件不能调用另一个组件中方法,这时需要把公共的方法或数据放到angular服务中,这样所有的组件都可以调用服务中的方法和数据,类型于vuex</li>
<li>使用步骤1(不推荐):</li>
</ul>
<pre><code class="language-ts">// 1. 创建服务
ng g service services/storage
// 2. 在根模块app.module.ts中引入并注册
import { StorageService } from './service/storage.service';
@NgModule({
providers: ,
})
// 3. 在创建的服务中编写公共的方法
export class StorageService {
get(){
    console.log("这是一个公共方法!");
}
}
// 4. 测试:在子组件search中使用;如果要在某个子组件中使用同样需映入并创建服务实例
import { StorageService } from '../../service/storage.service';
var storage = new StorageService;
export class SearchComponent implements OnInit {
constructor() {
    // 测试服务中的公共方法
    console.log(storage)
}
}
</code></pre>
<ul>
<li>使用步骤2(官方推荐):</li>
</ul>
<pre><code class="language-ts">/// 1. 创建服务
ng g service services/storage
// 2. 在根模块app.module.ts中引入并注册
import { StorageService } from './service/storage.service';
@NgModule({
providers: ,
})
// 3. 在创建的服务中编写公共的方法
export class StorageService {
get(){
    console.log("这是一个公共方法!");
}
}
// 4. 测试:在子组件search中使用;如果要在某个子组件中使用同样需映入并创建服务实例
import { StorageService } from '../../service/storage.service';
export class SearchComponent implements OnInit {
constructor( public storage: StorageService) {    // 相当于上面的new服务实例
    let s= this.storage.test();
    console.log(s);
}
}
</code></pre>
<h4 id="案例服务中编写公共方法">案例:服务中编写公共方法</h4>
<ul>
<li>angular服务中编写方法</li>
</ul>
<pre><code class="language-ts">export class StorageService {
// 事项清单添加数据到本地缓存
set(key: string, value: any){
    localStorage.setItem(key, JSON.stringify(value));
}
// 从本地缓存中获取数据
get(key: string){
    return localStorage.getItem(key);
}
// 删除本地缓存中的数据
remove(key: string){
    localStorage.removeItem(key);
}
}
</code></pre>
<ul>
<li>在search.component.ts中使用</li>
<li>在ts组件中ngOnInit方法会在每次刷新时触发</li>
</ul>
<pre><code class="language-ts">import { StorageService } from '../../service/storage.service';
// 1.引入
export class SearchComponent implements OnInit {
ngOnInit(): void {
    console.log("刷新页面时会触发该周期函数")
    // 2.每次刷新时都会从本地缓存中获取数据
    var searchlist: any= this.storage.get('searchlist');
    if(searchlist){
      this.historyList=searchlist;
      console.log("获取成功")
    }
    // console.log(this.storage.get('searchlist'))
    // let searchlist: any =this.storage.get('searchlist');   
    // this.historyList.push(searchlist);
}

doSearch(){
    if(this.historyList.indexOf(this.keyword)==-1){
      this.historyList.push(this.keyword);
      // 3.添加历史记录到本地缓存
      this.storage.set('searchlist', this.historyList);
      console.log("添加成功")
    }
    this.keyword='';
}
}
</code></pre>
<h4 id="dom节点操作">dom节点操作</h4>
<ul>
<li>方式一:</li>
</ul>
<pre><code class="language-ts">// html组件中有一个box节点
&lt;div id="box"&gt;这是一个盒子!&lt;/div&gt;

// ts组件中通过原生的js方法操作
ngOnInit(): void {
let box: any= document.getElementById('box');
console.log("dom" + box.innerHTML);
box.style.color="blue";
}
</code></pre>
<ul>
<li>方式二:</li>
</ul>
<pre><code class="language-ts">// html组件中的dom节点中有angular指令
&lt;div id="box2" *ngIf="flag"&gt;这是一个盒子!&lt;/div&gt;

// ts组件中,在ngAfterViewInit函数中操作,注意大小写,否则不起作用
ngAfterViewInit(): void {
    let box2: any= document.getElementById('box2');
    console.log("dom" + box2.innerHTML);
    box2.style.color="red";
}
</code></pre>
<ul>
<li>方式三:使用viewchild</li>
</ul>
<pre><code class="language-ts">// 1. html组件中自定义节点名称box3
&lt;div #box3 *ngIf="flag" &gt;这是一个盒子!&lt;/div&gt;

// 2. ts组件中操作,引入viewchild
import { ViewChild } from '@angular/core';
export class DomComponent implements OnInit {
public flag: boolean = true;

// 3. 使用viewchild,定义组件名称
@ViewChild('box3') box3: any;

ngAfterViewInit(): void {
    // 4. 使用
    console.log("box3" + this.box3.nativeElement);
    this.box3.nativeElement.style.color="red";
}
}
</code></pre>
<ul>
<li>使用viewChild调用另一个组件中的方法</li>
</ul>
<pre><code class="language-ts">// 例如dom组件调用form组件中的方法
// 1. 在dom组件的html中引入form组件,并指定名称
&lt;app-form #form&gt;&lt;/app-form&gt;

// 2. 在dom组件的ts组件中操作,引入viewchild
import { ViewChild } from '@angular/core';
export class DomComponent implements OnInit {
// 3. 使用viewchild,定义组件名称
@ViewChild('form') form: any;

ngAfterViewInit(): void {
    // 4. 调用form组件中的方法
    console.log("form -&gt; " + this.form.run());
}
}
</code></pre>
<h4 id="实现一个侧边栏">实现一个侧边栏</h4>
<ul>
<li>新建组件transition</li>
</ul>
<pre><code class="language-ts">// 编写html
&lt;div id="content"&gt;
    内容区&lt;br&gt;
    &lt;button (click)="showAside()"&gt;弹出侧边栏&lt;/button&gt;
    &lt;button (click)="hiddenAside()"&gt;隐藏侧边栏&lt;/button&gt;
&lt;/div&gt;
&lt;div id="aside"&gt;
    侧边栏
&lt;/div&gt;

// 全局样式
body{
    width: 100%;
    overflow-x: hidden;
}

// ts组件中
export class TransitionComponent implements OnInit {
showAside(){
    var asideDom = document.getElementById('aside');
    asideDom.style.transform = "translate(0,0)";
}
hiddenAside(){
    var asideDom = document.getElementById('aside');
    asideDom.style.transform = "translate(100%,0)";
}
}
</code></pre><br><br>
来源:https://www.cnblogs.com/dogleftover/p/17721450.html
頁: [1]
查看完整版本: Angular入门