小编AJT*_*T82的帖子

如何在Angular2/4/5中实现自定义异步验证器

1.它甚至得到了Angular的支持吗?看到这个开放的问题

2.如果是的话,什么是错在下面的代码

export class someClass{

    myForm:ControlGroup;

    constructor(public http:Http, public formBuilder:FormBuilder)
       this.myForm = formBuilder.group({
            ImageId: ["", Validators.required, this.asynValidator]
    });

    asyncValidator(control: Control): {[key: string]: any} {

        return new Promise (resolve => {

          let headers = new Headers();
          headers.append('Content-Type', 'application/json');

          this.http.get('http://localhost/ImageIdValidate?id='+ control.value, {headers:headers})
                .map(res => res.json())
                .subscribe(data => {
                    console.log(data);
                    if(data != null) {
                        resolve({"duplicate": true})
                    }
                    else resolve(null);      
                })
            });
        });
      }
    }
Run Code Online (Sandbox Code Playgroud)

它甚至没有提出服务器请求.

typescript angular

25
推荐指数
1
解决办法
2万
查看次数

与elvis-operator绑定的双向方式

使用elvis-operator在Angular 2中使用双向绑定(syntax-sugar)的最佳方法是什么?我试过了

    <input [(ngModel)]="x?.y?.z"> 
Run Code Online (Sandbox Code Playgroud)

但这不受支持.

有没有办法使用...... 像这样?

angular2-forms angular

16
推荐指数
1
解决办法
4674
查看次数

Angular 2-使用具有多个条件的*ngIf

我无法在导航栏上有选择地显示链接.根据谁登录(用户或管理员),我想更改导航栏上显示的链接.

以下是用户/管理员注销的一个此类实例的代码.

在navbar.component.html中 -

<li *ngIf="authService.userLoggedIn()== true && authService.adminLoggedIn() == false" 
       [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}"> 
  <a (click)="onUserLogoutClick()" href="#">Logout</a>
</li>

<li *ngIf="(authService.adminLoggedIn() == true) && (authService.userLoggedIn() == false)" 
      [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
   <a (click)="onAdminLogoutClick()" href="#">Logout</a>
</li>
Run Code Online (Sandbox Code Playgroud)

无论authService.adminLoggedIn()authService.userLoggedIn()回报tokenNotExpired;

以下是navbar.component.ts中的相关代码-

 onUserLogoutClick() {
   this.authService.userLogout();
   this.flashMessage.show('You are now logged out', {cssClass: 'alert-success', timeout: 3000});
   this.router.navigate(['/login']);
   return false;   
 }

 onAdminLogoutClick() {
   this.authService.adminLogout();
   this.flashMessage.show('Administrator now logged out', {cssClass: 'alert-success', timeout: 3000});
   this.router.navigate(['/admin']);
   return false;   
 }
Run Code Online (Sandbox Code Playgroud)

authService.adminLogout()authService.userLogout()刚刚清除存储在本地存储的令牌.

如果我犯的错误是愚蠢的,我会提前道歉.我是Angular的新手.

angular-ng-if angular

14
推荐指数
1
解决办法
6万
查看次数

如何在输入字段为空时添加"活动"类

我正在尝试创建一个Angular 4指令,class="active"当文本字段不为空时,该指令将添加到标签上

<div class="md-form">
    <input appMdbInputInit type="text" name="" id="FirstName" 
         class="form-control"   formControlName="firstName">
    <label  for="FirstName" >First Name</label>
 </div>
Run Code Online (Sandbox Code Playgroud)

当textfield不为空时我期望的结果

 <div class="md-form">
    <input  appMdbInputInit  type="text" name="" id="FirstName" 
         class="form-control"   formControlName="firstName">
    <label class="Active"  for="FirstName" >First Name</label>
 </div>
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?

非常感谢

angular2-directives angular

11
推荐指数
3
解决办法
4079
查看次数

Angular 4 - 如何让我的复选框更改变量的值?

我对Angular 4很新,我想将变量的值从"hours"更改为"days",并将我的ngModel给出的值除以8.我究竟要怎么做呢?

以下是我的summary.component.html的摘录:

<div class="onoffswitch">
  <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
  <label class="onoffswitch-label" for="myonoffswitch">
    <span class="onoffswitch-inner"></span>
    <span class="onoffswitch-switch"></span>
  </label>
</div>

<div class="panel-body">
    <form class="form-horizontal" role="form" style="overflow-x:auto;">
      <fieldset>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedIndex">
            <label class="col-xs-2" style="font-weight: bold;"> &#43; </label>
            <label class="col-xs-4"> Carryover </label>
            <div class="col-xs-6">
              <input class='form-control' type="text" id="ptoCarry" [(ngModel)]="empInfo[selectedIndex].PTOCarry + timeVar" name="ptoCarry"/>
            </div>
          </div>
        </div>
      </fieldset>
    </form>
</div>
Run Code Online (Sandbox Code Playgroud)

然后这是我的summary.component.ts:

import { Component, OnInit } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmpInfoService …
Run Code Online (Sandbox Code Playgroud)

checkbox angular

10
推荐指数
1
解决办法
5万
查看次数

使用angular2中的组件交互通过<router-outlet>传递数据

我正在尝试使用此技术拦截输入属性更改与setter将一些数据从父组件传递到子组件,并在更改值时调用子组件中的方法.我的问题是<router-link>,当我尝试使用以下方法传递数据时,子组件被绑定到父组件:

parent_component.html:

<router-outlet [some_value] = "some_value"></router-outlet>
Run Code Online (Sandbox Code Playgroud)

其中some_value是我试图从父传递到子传递的参数.

parent_component.ts:

public some_value: string;
Run Code Online (Sandbox Code Playgroud)

parent_component.ts:

@Input()
  public set some_vale(number : string){
    this._some_value = number;
  }
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误

未处理的Promise拒绝:模板解析错误:无法绑定到'some_value',因为它不是'router-outlet'的已知属性.

我究竟做错了什么?使用a时,将数据从父组件传递到子组件的正确方法是<router-outlet>什么?

在此先感谢,任何帮助表示赞赏.

angular2-routing angular-components router-outlet angular

9
推荐指数
1
解决办法
7395
查看次数

TypeError:error.json不是函数

编辑:阅读问题末尾的部分!

我收到此错误:在此输入图像描述在此输入图像描述

我的服务代码:

import { Http, Response, Headers } from "@angular/http";
import { Injectable } from "@angular/core";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from "rxjs";

import { Client } from "./client.model";

@Injectable()
export class ClientService {
    private clients: Client[] = [];

    constructor(private http: Http){}

    addClient(client: Client) {
        this.clients.push(client);
        const body = JSON.stringify(client);
        const headers = new Headers({'Content-Type': 'application/json'});
        return this.http.post('http://localhost:3000/client', body, {headers: headers})
            .map((response: Response) => response.json())
            .catch((error: Response) => Observable.throw(error.json()));
    }

    getClients() {
        return this.clients;
    }

    deleteClient(client: …
Run Code Online (Sandbox Code Playgroud)

angular

8
推荐指数
2
解决办法
3万
查看次数

如何使用Typescript在Angular 2中创建TreeView?

如何使用TypesScript在Angular 2中创建TreeView?

我试图在谷歌上找到但仍然没有得到任何有效的例子等.

任何人都可以分享我的例子来实现这个任务吗?

treeview typescript angular

7
推荐指数
1
解决办法
2万
查看次数

如何从实现ControlValueAccessor的组件引用FormControl?

我创建了一个源自此博客文章的Angular组件.我有一个被动的形式,我想在窗体控件上得到错误,组件本身将有一个程式化的错误消息,它将在控件有错误时呈现.但是,当我尝试将NgControl类注入组件时,我得到循环引用问题,那么我将如何访问控件上的错误?

这是当前的代码,它还没有完成,但它应该给出我想要完成的基本想法:

import { Component, Output, EventEmitter, Input, forwardRef } from '@angular/core';
import {
    NgControl,
    NG_VALUE_ACCESSOR,
    ControlValueAccessor,
    Validator,
    AbstractControl,
    FormControl,
    NG_VALIDATORS
} from '@angular/forms';

@Component({
    selector: 'form-field-input',
    templateUrl: './form-field-input.component.html',
    styleUrls: ['./form-field-input.component.less'],
    providers: [{
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => FormFieldInputComponent),
        multi: true
    }]
})
export class FormFieldInputComponent implements ControlValueAccessor {

    private propagateChange = (_: any) => { };
    private propagateTouch = (_: any) => { };

    @Input('label') label: string;
    @Input('type') type: string;
    @Input('id') id: string;
    @Input('formControlName') formControlName: string;
    @Input('error') …
Run Code Online (Sandbox Code Playgroud)

angular

7
推荐指数
1
解决办法
2033
查看次数

函数被多次调用

我想显示一个dataList.某些值是从函数计算的.似乎angular2多次调用计算函数.

  <tr *ngFor="let data of dataList">
    <td>{{ data.no }}</td>
    <td>{{ data.name }}</td>
    <td>{{ calculateFunction(data.price) }}</td>
  </tr>
Run Code Online (Sandbox Code Playgroud)

控制台将多次输出"calculate ...",超过dataList.length.

calculateFunction() {
  console.log('calculate...');
  return ...;
}
Run Code Online (Sandbox Code Playgroud)

我应该担心性能还是让angular2这样做?

ngfor angular

7
推荐指数
2
解决办法
4133
查看次数