关于angular 2 的一些随便

学习网站:http://angular.cn/

第一个“hello word” 很难,希望努力

1.npm install -g @angular/cli(第一次) /npm install @angular/cli  / npm install 针对已有的项目,装载依赖
2.ng new my-app
3.cd my-app
ng serve --open
4.ng generate component(c) heroes
5.ng generate service(s) hero
6.ng generate module(m) app-routing --flat --module=app      
7.npm install angular-in-memory-web-api --save
8.ng generate component hero -it  覆盖
9.ng generate class hero
10.ng generate directive(d) highlight
11.ng generate pipe(p) exponential-strength
12.E:\学习\vscode\angular4\my-app\src\app\directive>ng generate directive test
13.ng generate module CustomerDashboard
14. ng new customer-app --routing (创建一个新项目)   ng generate module customers --routing    ng generate component customers/customer-list 子文件夹
15.npm install jquery --save  /  npm install bootstrap--save --写入package
16.npm install admin-lte --save
17.ng build - 构建/编译应用
18.ng build --prod   打包发布
==============================================

ng2 的创建命令

ng new project-name - 创建一个新项目,置为默认设置

    ng new project-name - 创建一个新项目,置为默认设置
    ng build - 构建/编译应用
    ng test - 运行单元测试
    ng e2e - 运行端到端(end-to-end)测试
    ng serve - 启动一个小型web服务器,用于托管应用
    ng deploy - 即开即用,部署到Github Pages或者Firebase


执行这些步骤所需要的全部设置,都由CLI工具来完成。

除了设置一个新应用之外,该工具还支持开发者运行命令,构建应用的组成部分,如组件(Component)和路由(Route)。

ng generate component my-comp - 生成一个新组件,同时生成其测试规格和相应的HTML/CSS文件

    ng generate directive my-directive - 生成一个新指令
    ng generate pipe my-pipe - 生成一个新管道
    ng generate service my-service - 生成一个新服务
    ng generate route my-route - 生成一个新路由
    ng generate class my-class - 生成一个简易的模型类

引用 SCSS

第一步:

你可以在创建项目的时候用

ng new sassy-project --style=scss

或者通过ng set defaults.styleExt scss 来修改你现有的项目;

ng set defaults.styleExt scss

第二步:

利用npm工具安装sass依赖和loader(npm不行可以试着cnpm)

npm install node-sass --save-dev
npm install sass-loader --save-dev

第三步:

修改.angular-cli.json文件
复制代码

"styles": [
    "styles.scss"
],
"defaults":{
    "styleExt": "scss",
    "component": {}
}

 
 

 
=================快捷方式==========================

回退:alt+左右箭头
关闭终端:ctrl+9
打开终端:ctrl+shift+`
命令设置窗口:ctrl+shift+p
格式化代码:ctrl+k+f
打卡试图:ctrl+shift+E
关闭当前窗口:ctrl+w
关闭所有编辑窗口:ctrl+K+W
打开快捷键设置:ctrl+k+s
引用修补:ctrl+.
====================控件网站==============================
https://www.angular.cn/resources 各大厂商集成

https://material.angular.io/
https://ng.ant.design/docs/introduce/zh
http://appwork.nicethemes.cn/layouts_layout-1.html
http://ngx-bootstrap.com/#/pagination
===========经验================
1.ngform 报错 module 块要 引用FormModule,httpclientmodule 可以放在基类。
2.第三方样式和脚本引用遵循typescript install 方法
3.ngform.clear();
4.module相互引用造成循环依赖
5.([object Object], ?, ?) 报错 ,尽量把常用类型?转成对象;
7.for 循环用法

<p>
  I turned the corner
  <ng-container *ngIf="hero">
    and saw {{hero.name}}. I waved
  </ng-container>
  and continued on my way.
</p>

<select [(ngModel)]="hero">
  <ng-container *ngFor="let h of heroes">
    <ng-container *ngIf="showSad || h.emotion !== 'sad'">
      <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>
    </ng-container>
  </ng-container>
</select>


8.complete: () => console.log('Observer got a complete notification')
() => console.log('Observer got a complete notification')

9.分配空 Object.assign({}, auth)
10.url:
  this.router.navigate([redirectUrl]);
            this.router.navigateByUrl(redirectUrl);
11.转JSON :JSON.parse(back) as ModuleNews[];         JSON.stringify(backCode.modulenews)        
12.代码click事件注册
function clickHandler(event) {
    console.log('用户已点击确认按钮!');
}
document.getElementById("btn").addEventListener('click', clickHandler);
13.监听浏览器改变

1)
ngOnInit() {

  // 页面监听
  Observable.fromEvent(window, 'resize')
    .debounceTime(100) // 以免频繁处理
    .subscribe((event) => {
    // 这里处理页面变化时的操作
      console.log('come on ..');
    });
}
2)
<div (window:resize)="onResize($event)"

onResize(event) {
  event.target.innerWidth;
}

3)

@HostListener('window:resize', ['$event'])
onResize(event) {
  event.target.innerWidth;
}

 
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }
 
  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }
 
  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
14. EventEmitter 只是一个帮你实现观察者模式①的对象。也就是说,它是一个管理一系列订阅者并向其发布事件的对象
1)
let ee = new EventEmitter();
ee.subscribe((name: string) => console.log(`Hello ${name}`));
ee.emit("Nate");
// -> "Hello Nate"

2)
@Component({
    selector: 'single-component',
    outputs: ['putRingOnIt'],
    template: `
<button (click)="liked()">Like it?</button>
`
})
class SingleComponent {
    putRingOnIt: EventEmitter<string>;
    constructor() {
        this.putRingOnIt = new EventEmitter();
    }
    liked(): void {
        this.putRingOnIt.emit("oh oh oh");
    }
}
15.获取页面上HTML动态调用模板(“<htmltemplate> #alerttemplate”)
    1).@ViewChild('alerttemplate')  template: TemplateRef<any>;
16.获取的页面上 动态调用子空间
      @ViewChild(CountdownTimerComponent)
      private timerComponent: CountdownTimerComponent;
     ngAfterViewInit(){}
17.ng-template 不向页面输入任何标记

ng-template [ngIf]="lessons" [ngIfElse]="loading">
   <div class="lessons-list">
     ...
   </div>
</ng-template>

<ng-template #loading>
    <div>Loading...</div>
</ng-template>
18.ng-container   为了避免创建额外的div,ng-container 还有另一个主要用途:它还可以提供一个占位符,用于将模板动态注入到页面中。
我们可以使用 ng-container:

<ng-container *ngIf="lessons">
    <div class="lesson" *ngFor="let lesson of lessons">
        <div class="lesson-detail">
            {{lesson | json}}
        </div>
    </div>
</ng-container>
18.1 <ng-template> 与 <ng-container> 区别
<ng-template>
<ng-template> 用于定义模板,使用 * 语法糖的结构指令,最终都会转换为 <ng-template> 模板指令,模板内的内容如果不进行处理,是不会在页面中显示。
<ng-container>
<ng-container> 是一个逻辑容器,可用于对节点进行分组,但不作为 DOM 树中的节点,它将被渲染为 HTML中的 comment 元素,它可用于避免添加额外的元素来使用结构指令。
18.2 TemplateRef与ViewContainerRef区别
TemplateRef
TemplateRef 实例用于表示模板对象。
ViewContainerRef
ViewContainerRef 实例提供了 createEmbeddedView() 方法,该方法接收 TemplateRef 对象作为参数,并将模板中的内容作为容器 (comment 元素) 的兄弟元素,插入到页面中。

19.ngTemplateOutlet 指令创建动态模板 和Template Context (模板的上下文)
NgTemplateOutlet 指令作用
该指令用于基于已有的 TemplateRef 对象,插入对应的内嵌视图。在应用 NgTemplateOutlet 指令时,我们可以通过 [ngTemplateOutletContext] 属性来设置 EmbeddedViewRef 的上下文对象。绑定的上下文应该是一个对象,此外可通过 let 语法来声明绑定上下文对象属性名。
友情提示:若 let 语法未绑定任何属性名,则上下文对象中 $implicit 属性,对应的值将作为默认值。
NgTemplateOutlet 指令语法
<ng-container *ngTemplateOutlet="templateRefExp; context: contextExp"></ng-container>

 例子 1) @Component({
  selector: 'app-root',
  template: `      
<ng-template #estimateTemplate let-lessonsCounter="estimate">
    <div> Approximately {{lessonsCounter}} lessons ...</div>
</ng-template>
<ng-container
   *ngTemplateOutlet="estimateTemplate;context:ctx">
</ng-container>
`})
export class AppComponent {
    totalEstimate = 10;
    ctx = {estimate: this.totalEstimate};
}

@Component({
  selector: 'app-root',
  template: `      
<ng-template #estimateTemplate let-lessonsCounter="estimate">
    <div> Approximately {{lessonsCounter}} lessons ...</div>
</ng-template>
<ng-container
   *ngTemplateOutlet="estimateTemplate;context:ctx">
</ng-container>
`})
export class AppComponent {
    totalEstimate = 10;
    ctx = {estimate: this.totalEstimate};
}
下面我们对这个例子进行一下解析:
- 这个模板与前面的模板不同,它有一个输入变量(它也可以有几个)。
- 输入变量为 lessonsCounter,它是通过 ng-template 属性使用前缀 let- 定义的。
- 在 ng-template 内可见 lessonsCounter,但在外部不可见。
- 这个变量的内容是由其赋值给属性的表达式决定的。
- 该表达式是针对上下文对象进行求值的,与模板一起传递到 ngTemplateOutlet,以实例化
- 该上下文对象必须具有key为“estimate”的属性,以便在模板内显示其值。
- 上下文对象通过上下文属性传递给 ngTemplateOutlet,它可以接收任何对对象进行计算的表达式。
例子 2 )
 @Component({
  selector: 'ng-template-outlet-example',
  template: `
    <ng-container *ngTemplateOutlet="greet"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="eng; context: myContext"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="svk; context: myContext"></ng-container>
    <hr>
    <ng-template #greet><span>Hello</span></ng-template>
    <ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>
    <ng-template #svk let-person="localSk"><span>Ahoj {{person}}!</span></ng-template>
`
})
class NgTemplateOutletExample {
  myContext = {$implicit: 'World', localSk: 'Svet'};
}

 <!-- let-param 取的是绑定对象myContext的$implicit字段的指,let-param相和let-param="$implicit"是等价的, -->
 <!-- let-name="name" 取的是绑定对象myContext里面name字段对应的值-->
 <ng-template #inputTemplateWithContent let-param let-name="name">
 <div>{{param}} - {{name}}</div> </ng-template>
 <ng-container *ngTemplateOutlet="inputTemplateWithContent; context: myContext">
 </ng-container>
 

20.Template References (模板引用)
1) 可以使用模板引用来引用加载模板,也可以使用 ViewChild 装饰器将一个模板直接注入到我们的组件中
@Component({
  selector: 'app-root',
  template: `      
      <ng-template #defaultTabButtons>
          <button class="tab-button" (click)="login()">
            {{loginText}}
          </button>
          <button class="tab-button" (click)="signUp()">
            {{signUpText}}
          </button>
      </ng-template>
`})
export class AppComponent implements OnInit {
    @ViewChild('defaultTabButtons')
    private defaultTabButtonsTpl: TemplateRef<any>;

    ngOnInit() {
        console.log(this.defaultTabButtonsTpl);
    }
}
2)可配置组件通过 @Input 导入部分模板
@Component({
  selector: 'app-root',
  template: `      
<ng-template #customTabButtons>
    <div class="custom-class">
        <button class="tab-button" (click)="login()">
          {{loginText}}
        </button>
        <button class="tab-button" (click)="signUp()">
          {{signUpText}}
        </button>
    </div>
</ng-template>
<tab-container [headerTemplate]="customTabButtons"></tab-container>      
`})
export class AppComponent implements OnInit {
}

@Component({
    selector: 'tab-container',
    template: `
<ng-template #defaultTabButtons>
    <div class="default-tab-buttons">
        ...
    </div>
</ng-template>
<ng-container
  *ngTemplateOutlet="headerTemplate ? headerTemplate: defaultTabButtons">

</ng-container>
... rest of tab container component ...
`})

export class TabContainerComponent {
    @Input()
    headerTemplate: TemplateRef<any>;
}

- 对于选项卡按钮定义了默认模板,命名为defaultTabButtons
- 只有当输入属性标题模板未定义时,才会使用 defaultTabButtons 模板
- 如果定义了输入属性,则将通过 headerTemplate 模板传递的自定义输入模板用于显示按钮
- headerTemplate 模板通过 ngTemplateOutlet 属性在 ng-container 内实例化
- 使用三元表达式来决定使用哪个模板(默认或自定义),但是如果逻辑复杂,我们也可以把它委托给控制器方法。
21.ng-content
  1)
 @ContentChild(TemplateRef) template: TemplateRef;
 @ContentChild('section_child_0') childOne: ContentChildComponent; // 通过 ContentChildComponent 组件名获取组件 @ContentChildren(ContentChildComponent) childrenList: QueryList<ContentChildComponent>;
  2)
  <ng-content select="div"></ng-content>
  <ng-content select=".select-class"></ng-content>
  <ng-content select="[name=test]"></ng-content>
  <div name="test">我是第一号位置 div[name="test"]</div>
  强调一点select的值不能设置为动态的
  3) 例子
   @Component({ selector: 'app-content-section',
   template: `
   <div> <h1>ng content</h1>
    div style="
       <ng-content select="app-content-child">
       </ng-content>
   </div>
   </div> `,
   styleUrls: ['./content-section.component.less'] })
22.ngOnChanges 和 ngDoCheck 区别 为了提高变化检测的性能,对于对象比较,Angular 内部直接使用 === 运算符进行值比较。因此当输入属性是引用类型,当改变对象内部属性时,是不会调用 ngOnChanges 生命周期钩子的

23.RouterLink  路由

<a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
   link to user component
</a>
/user/bob#education?debug=true

    merge - 合并已有的 queryParams 到当前的 queryParams 中

    preserve - 保存当前的 queryParams

    default ('') - 仅使用查询参数
<a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
    link to user component
</a>
<a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
<a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
<a routerLink="/user/bob" routerLinkActive="active-link"
  [routerLinkActiveOptions]="{exact: true}">Bob</a>
 
  <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
    Bob {{ rla.isActive ? '(already open)' : ''}}
</a>

<div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>
组件模板设置

<router-outlet></router-outlet>

2).多路由处理

{ path: 'news', outlet: 'let1', component: NewsComponent },
{ path: 'news', outlet: 'let2', component: News2Cmponent },
//模板中

<router-outlet name="let1"></router-outlet>
<router-outlet name="let2"></router-outlet>

访问 /news/ 时同时加载 NewsComponent 和 News2Cmponent 两个组件

3).路有链接以及组件中调用路由方法使用

<a routerLink="/detail/1" routerLinkActive="active">detail</a>
<a [routerLink]="['/detail', news.id]">{{news.title}}</a>
<a [routerLink]="[{ outlets: { let2: ['news'] } }]">Contact</a>

routerLinkActive="active" 即在本路由激活时添加样式 .active

或者:

this.router.navigate(['/detail', this.news.id])
this.router.navigate([{ outlets: { let2: null }}]);

其中:navigateByUrl 方法指向完整的绝对路径
4)静态路由
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';

export const ROUTES: Routes = [
  { path: '', component: HomeComponent },
  { path: '/profile/:username', component: ProfileComponent }
];
5)Child routes

export const ROUTES: Routes = [
  {
    path: 'settings',
    component: SettingsComponent,
    children: [
      { path: 'profile', component: ProfileSettingsComponent },
      { path: 'password', component: PasswordSettingsComponent }
    ]
  }
];

@Component({
  selector: 'settings-page',
  template: `
    <div class="settings">
      <settings-header></settings-header>
      <settings-sidebar></settings-sidebar>
      <router-outlet></router-outlet>
    </div>
  `
})



6)参数传递
<a [routerLink]="['/profile', username]">
  Go to {{ username }}'s profile.
</a>


this.router.navigate(['/profile', event.name]);


export class AppComponent implements OnInit {
  users: Username[] = [
    { name: 'toddmotto', id: 0 },
    { name: 'travisbarker', id: 1 },
    { name: 'tomdelonge', id: 2 }
  ];
 
  constructor(private router: Router) {}
 
  handleSelect(event) {
    this.router.navigate(['/profile', event.name]);
  }
}

获取参数


export class SettingsComponent implements OnInit {
  username: string;
  constructor(private route: ActivatedRoute) {}
  ngOnInit() {
    this.route.params.subscribe((params) => this.username = params.username);
  }
}
====================安全==================
constructor(private sanitizer: DomSanitizer) {
  // javascript: URLs are dangerous if attacker controlled.
  // Angular sanitizes them in data binding, but you can
  // explicitly tell Angular to trust this value:
  this.dangerousUrl = 'javascript:alert("Hi there")';
  this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
<p><a class="e2e-dangerous-url" [href]="dangerousUrl">Click me</a></p>

<iframe class="e2e-iframe-trusted-src" width="640" height="390" [src]="videoUrl"></iframe>
<iframe class="e2e-iframe-untrusted-src" width="640" height="390" [src]="dangerousVideoUrl">
  this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id;
  this.videoUrl =
      this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl);
==================生命周期=====================


 钩子
    

用途及时机

1.ngOnChanges()
    

当 Angular(重新)设置数据绑定输入属性时响应。 该方法接受当前和上一属性值的 SimpleChanges 对象

当被绑定的输入属性的值发生变化时调用,首次调用一定会发生在 ngOnInit() 之前。

2.ngOnInit()
    

在 Angular 第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件。

在第一轮 ngOnChanges() 完成之后调用,只调用一次。

3.ngDoCheck()
    

检测,并在发生 Angular 无法或不愿意自己检测的变化时作出反应。

在每个 Angular 变更检测周期中调用,ngOnChanges() 和 ngOnInit() 之后。

4.ngAfterContentInit()
    

当把内容投影进组件之后调用。

第一次 ngDoCheck() 之后调用,只调用一次。

5.ngAfterContentChecked()
    

每次完成被投影组件内容的变更检测之后调用。

ngAfterContentInit() 和每次 ngDoCheck() 之后调用

6.ngAfterViewInit()
    

初始化完组件视图及其子视图之后调用。

第一次 ngAfterContentChecked() 之后调用,只调用一次。

7.ngAfterViewChecked()
    

每次做完组件视图和子视图的变更检测之后调用。

8.ngAfterViewInit() 和每次 ngAfterContentChecked() 之后调用。

ngOnDestroy()
    

当 Angular 每次销毁指令/组件之前调用并清扫。 在这儿反订阅可观察对象和分离事件处理器,以防内存泄漏。

在 Angular 销毁指令/组件之前调用。

转载于:https://www.cnblogs.com/memezhu/p/10120194.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值