关于Angular2指令,我想使用outputs而不是使用@Output因为我有很多自定义事件并且想要保持DRY.
但是,我有TypeError: Cannot read property 'subscribe' of undefined,而且我不知道为什么会这样.
http://plnkr.co/edit/SFL9fo?p=preview
import { Directive } from "@angular/core";
@Directive({
selector: '[my-directive]',
outputs: ['myEvent']
})
export class MyDirective {
constructor() {
console.log('>>>>>>>>> this.myEvent', this.myEvent);
}
}
Run Code Online (Sandbox Code Playgroud)
这是使用此指令的app组件
我需要将现有的Angular 2 RC 1应用程序迁移到Angular 2 RC 4.作为其中的一部分,我还需要将现有的表单移动到Angular 2 RC 4 New Forms.
任何人都可以指导,如何将现有表格更新为新表格.
angular2-forms angular2-directives angular2-template angular
我开始使用Angular2(最终版本),我在使用*ngFor时遇到了一些问题.
我已经构建了以下组件树:main - > dashboard - > alerts
未处理的Promise拒绝:模板解析错误:无法绑定到'ngForOf',因为它不是'div'的已知属性.
("<div class ="item"[ERROR - >]*ngFor ="让警报提醒">"):DashboardAlertsComponent @ 5:20属性绑定ngForOf未被嵌入式模板上的任何指令使用.
确保属性名称拼写正确,并且所有指令都列在"指令"部分中.
它工作正常,但当我尝试在警报组件中添加*ngFor循环时,我收到以下错误:
DashboardAlertsComponent:
import {Component, OnInit} from "@angular/core";
import {Alert} from "../../shared/models/alert.model";
@Component({
selector: 'dashboard-alerts',
templateUrl: './alerts.component.html'
})
export class DashboardAlertsComponent implements OnInit {
alerts:Alert[] = new Array<Alert>();
constructor() {
this.alerts.push(new Alert('1', 'high', 'My alert1', '12/11/2016 4:50 PM'));
this.alerts.push(new Alert('2', 'low', 'My alert2', '11/11/2016 9:50 PM'));
this.alerts.push(new Alert('3', 'medium', 'My alert3', '10/11/2016 2:50 PM'));
}
ngOnInit() {
}
}
Run Code Online (Sandbox Code Playgroud)
alerts.component.html
<div class="item" …Run Code Online (Sandbox Code Playgroud) 使用
TouchEvent
Run Code Online (Sandbox Code Playgroud)
在指令中输入会导致Safari桌面出现以下错误
ReferenceError: Can't find variable: TouchEvent
Run Code Online (Sandbox Code Playgroud)
Typescript源代码是
@HostListener('touchstart', ['$event'])
onTouchstart(event: TouchEvent) {
// ... does something with event.
}
Run Code Online (Sandbox Code Playgroud)
生成的错误代码是
__decorate([
core_1.HostListener('touchstart', ['$event']),
__metadata('design:type', Function),
__metadata('design:paramtypes', [TouchEvent]),
__metadata('design:returntype', void 0)
], MyTouchDirective.prototype, "onTouchstart", null);
Run Code Online (Sandbox Code Playgroud)
将类型更改为
any
Run Code Online (Sandbox Code Playgroud)
修复,但是应该可以使用这种类型吗?我一般认为类型永远不会产生javascript.我在同一程序中的Typescript类中有其他对TouchEvent的引用,这些引用不会导致问题.
我开发了一个自定义指令,用于修剪输入控件的值.请找到相同的代码:
import { Directive, HostListener, Provider } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[ngModel][trim]',
providers: [NgModel],
host: {
'(ngModelChange)': 'onInputChange($event)',
'(blur)': 'onBlur($event)'
}
})
export class TrimValueAccessor {
onChange = (_) => { };
private el: any;
private newValue: any;
constructor(private model: NgModel) {
this.el = model;
}
onInputChange(event) {
this.newValue = event;
console.log(this.newValue);
}
onBlur(event) {
this.model.valueAccessor.writeValue(this.newValue.trim());
}
}
Run Code Online (Sandbox Code Playgroud)
问题是ngModel没有更新onBlur事件的值.我试图修改onModelChange事件的值,但它不允许两个单词之间的空格(例如,ABC XYZ)
任何建议都会有所帮助.
我正在尝试创建一个在输入中接受icon属性的指令,该属性将是图标名称.所以内部指令会尝试找到一个span应用类的元素.我想知道这是否可以从应用于父代的指令中实现.或者我是否也必须为孩子创建一个指令?
这是我的HTML代码:
<div sfw-navbar-square sfw-navbar-icon>
<span class="mdi mdi-magnify"></span>
</div>
Run Code Online (Sandbox Code Playgroud)
这是指令本身:
import { Directive, ElementRef, Renderer } from '@angular/core';
@Directive({
selector: '[sfw-navbar-square]'
})
export class NavbarSquareDirective {
// Here I'd like to define a input prop that takes a string
constructor(private el: ElementRef, private renderer: Renderer) {
this.renderer.setElementClass(this.el.nativeElement, 'navbar-square-item', true);
this.renderer.setElementClass(this.el.nativeElement, 'pointer', true);
this.renderer.setElementClass(this.el.nativeElement, 'met-blue-hover', true);
// Here I'd like to pass that string as a class for the span child element. Can I have access to …Run Code Online (Sandbox Code Playgroud) 我创建了img-pop组件,它具有@Input()绑定属性src.我创建了authSrc指令,它具有@HostBinding()属性src.
@Component({
selector: 'img-pop',
template: `<img [src]="src"/>
<div *ngIf="isShow">
<----extra value----->
</div>`
})
export class ImgPopOverComponent implements OnInit {
@Input()
private src;
private isShow=false;
@HostListener('mouseenter') onMouseEnter() {
this.isShow= true;
}
@HostListener('mouseleave') onMouseLeave() {
this.isShow= false;
}
}
Run Code Online (Sandbox Code Playgroud)
我有这样的指示.
@Directive({ selector: '[authSrc]' })
export class AuthSrcDirective implements OnInit {
@HostBinding()
private src: string;
constructor(private element: ElementRef) { }
ngOnInit() { }
@Input()
set authSrc(src) {
this.src = src+"?access_token=<-token->";
}
}
Run Code Online (Sandbox Code Playgroud)
我希望将两种功能结合在一起.
<img-pop [authSrc]="/api/url/to/image"></img-pop>
Run Code Online (Sandbox Code Playgroud)
所以最终的url调用将是/ api/url/to/image?access_token = < …
angular2-directives angular-components angular2-hostbinding angular
题:
是否可以以@HostBinding这种方式在主机元素上添加,删除或切换类而不删除预先存在的类,特别是在需要动态切换类时?
例如,这将添加light类并且对前面的类light没有破坏性;但是,不能是动态的.
想象一下这个渲染的dom节点:
<div [classToggler] class="someClasses1 someClasses2' ></div>
Run Code Online (Sandbox Code Playgroud)
有了这个控制器:
@HostBinding('class.light') isLight = theme === 'light'; // true
ngOnInit() {
this.store.select('classToggler').subscribe((className) => {
this.theme = className || 'light'
});
}
Run Code Online (Sandbox Code Playgroud)
作为这个示例控制器,将动态添加light类,但据我所知,将删除host元素上的其他类.
@HostBinding('class') theme;
ngOnInit() {
this.store.select('classToggler').subscribe((className) => {
this.theme = className || 'light'
});
}
Run Code Online (Sandbox Code Playgroud)
最后,第二个示例将重新呈现dom元素,如下所示:
<div [classToggler] class="light'></div>
Run Code Online (Sandbox Code Playgroud)
因此,删除以前的类,这是不希望的.关于如何充分利用这两个世界的任何想法?
我试图在运行时将角度代码的*ngIf指令分配给模板.无法找到办法.view/templateref是一个选项吗?或者有一个不同的方式和一个更容易的方式.有可能首先吗?
更新:
代码有点混乱和混乱,所以避免它.但是这里是DOM代码的外观,以及为什么我需要动态添加内置结构指令.
<div>
<input type="text" [value]="userProvidedValue">
<textarea [value]="someDynamicDOMCodefromWYSIWYG">
<!-- user provided provided code or dynamic code -->
</textarea>
</div>
<div>
<select *ngIf="fetchArraywithHttpFromuserProvidedValue">
<option *ngFor="let val of fetchArraywithHttpFrom-userProvidedValue" value=""></option>
</select>
</div>
<div>
<ng-template>
<!-- Some User provided code or dynamic code which might need to use *ngIf OR *ngFor -->
<!-- The *ngIf OR *ngFor will be added dynamically based on a manipulator function which is decided from the value of fetchArraywithHttpFromuserProvidedValue -->
</ng-template>
</div>
Run Code Online (Sandbox Code Playgroud)
我正在根据userProvidedValue值执行获取请求,并且获取请求的结果决定了fetchArraywithHttpFromuserProvidedValue …
我正在尝试创建自定义angular 2验证器指令,它会像这样注入NgControl:
@Directive({
selector: '[ngModel][customValidator]',
providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
})
export class CustomValidatorDirective implements Validator {
private validateFunction: ValidatorFn;
constructor(private control: NgControl) { };
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
无法实例化循环依赖!NgControl
有谁知道我可以如何工作,所以我可以在初始化后访问ngControl?