标签: angular5

Angular 5 [对象 HTMLDivElement]

当我单击按钮时,我将“copyRow”元素发送到“copyItem”方法。我将“copyItem”元素与“Typescript”文件中的“item”变量进行均衡。

当我想显示“[object htmldivelement]”时,这个“html 文件中的项目”变量将作为输出。

创建.component.html

<div class="questions">
    <div class="form-group copy-row" #copyRow>
       <label>Question</label>
       <input type="text" class="form-control" placeholder="Question title">
    </div>
    {{ item }}
</div>
<button type="button" class="btn btn-primary" (click)="copyItem(copyRow)">Add</button>
Run Code Online (Sandbox Code Playgroud)

创建组件.ts

  item;

  constructor() { }

  ngOnInit() {
  }

  copyItem(row) {
    this.item = row;
  }
Run Code Online (Sandbox Code Playgroud)

编辑

我的目标是做一个调查项目。当我单击“添加”按钮时,相同的“#copyRow”元素将显示在 {{ item }} 部分中。但是,我得到了类似于第二个链接的输出。

1: http: //prntscr.com/j1ncp1 2: http: //prntscr.com/j1nd19

html typescript angular angular5

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

.ts 文件可以包含多个类吗

我想创建一个.ts包含我的数据模型的文件。每个数据模型都映射到一个JSON我将从服务器发送或接收的数据。例如。对于用户个人资料,Json 是

 {
  "firstname" : "d",
  "lastname" : "d",
  "email" : "dd",
  "password" : "d"
}
Run Code Online (Sandbox Code Playgroud)

对于上面的内容,我想创建一个类,如下所示

export class UserProfile {

  constructor (public firstname:string,
               public lastname:string,
               public email:string,
               public password:string){}
}
Run Code Online (Sandbox Code Playgroud)

服务器可能发送的另一个 JSON 是

{
result:"success"
addition-info:"something"
}
Run Code Online (Sandbox Code Playgroud)

上面的类是

export class Result{

  constructor (public result:string,
               public additionalInfo:string){}
}
Run Code Online (Sandbox Code Playgroud)

Angular 中是否有关于如何为数据模型创建文件的最佳实践?我可以创建一个.ts文件BackendApiModels.ts来存储所有类,还是应该.ts为每个数据模型创建一个文件?我什至不知道是否可以创建一个.ts可以包含多个类的文件,例如

后端API

 export class UserProfile {

      constructor (public firstname:string,
                   public lastname:string,
                   public email:string,
                   public password:string){}
    }

    export class Result{ …
Run Code Online (Sandbox Code Playgroud)

angular5

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

HammerJS 无法在移动设备上使用 Angular Material 2 选项卡。

我正在尝试将滑动手势集成到 Angular 材料 2(Angular5) 中。它在桌面上使用鼠标工作。问题是,当我使用移动设备(Chrome)时,它只感知选项卡标签上的手势。

模板代码:

<mat-tab-group mat-scroll-y (swipeleft)="swipe($event.type)" (swiperight)="swipe($event.type)" class="home-tabs" mat-stretch-tabs [(selectedIndex)]="selectedIndex">
    <mat-tab label="Home">
      <ng-template mat-tab-label>
        <mat-icon>home</mat-icon>
      </ng-template>
      <app-my-cars></app-my-cars>
    </mat-tab>
    <mat-tab label="Registered Cars">
      <ng-template mat-tab-label>
        <mat-icon>directions_car</mat-icon>
      </ng-template>
      <app-registered-cars></app-registered-cars>
    </mat-tab>
    <mat-tab label="Unregistered Cars">
      <ng-template mat-tab-label>
        <mat-icon>directions_car</mat-icon>
      </ng-template>
      <app-unregistered-cars></app-unregistered-cars>
    </mat-tab>
  </mat-tab-group>
Run Code Online (Sandbox Code Playgroud)

组件代码:

export class DashboardHomeComponent implements OnInit {
  constructor() { }

  ngOnInit() {
  }
  selectedIndex: number = 0;
  totalTabs: number = 3;
  SWIPE_ACTION = { LEFT: 'swipeleft', RIGHT: 'swiperight' };
  swipe(eType) {
    console.log(eType)
    if(eType === 'swipeleft' && this.selectedIndex < this.totalTabs){
      this.selectedIndex …
Run Code Online (Sandbox Code Playgroud)

hammer.js angular-material angular-material2 angular angular5

5
推荐指数
0
解决办法
662
查看次数

如何以反应形式为 datetime-local 赋值

我无法为表单中的“datetime-local”元素赋值。

模板中的代码:

HTML 模板中的代码

打字稿文件中的代码:

let dateTime : Date = new Date();

this.testForm = this.formBuilder.group({    
  'dateTime': new FormControl(dateTime),
});
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

使用打字稿将日期和时间分配给 datetime-local 的正确方法是什么

angular angular-reactive-forms angular5

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

Angular5在数组中插入元素,同时用ngfor显示它

我有一个对象数组(config.lensTab),我在 Html 中使用 ngFor 显示这些对象:

<tr *ngFor="let item of config.lensTab; let i = index;">
          <th scope="row">{{ i + 1}}</th>
          <th><label></label>
          <input [(ngModel)]="item.radius" class="form-control"
                             type="number" step="0.01" name="radius-{{i}}</th>
[...]
Run Code Online (Sandbox Code Playgroud)

我添加了一个“+”按钮,它将在数组中的给定索引(idx)中插入一个元素:

  public addLens(idx: number) {
           let toAdd = new LensModel(0, 0, 0,
           new MaterialModel('Air', 0), 0, 0);
           this.config.lensTab.splice(idx + 1, 0, toAdd);
     }
Run Code Online (Sandbox Code Playgroud)

当我用 console.log 显示数组的内容时,插入操作似乎工作正常。然而,在我的 html 视图中,新行旁边的行与该新行具有相同的值。

我给你一个简单的例子来帮助理解:

Tab : [RED, GREEN, WHITE] --> add "BLUE" at index 1 ---> [RED, BLUE, BLUE, WHITE]
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?

编辑:这就是我初始化配置对象的方式

this.config = new ConfigModel(); …
Run Code Online (Sandbox Code Playgroud)

html typescript angular angular5

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

无法绑定到 Directive('appHasAccess'),因为它不是“input”的已知属性

我创建了一个自定义属性指令库包并将其安装到 myProject 中,当我尝试使用此自定义指令时会引发错误。

错误错误:未捕获(承诺):错误:模板解析错误:无法绑定到“appHasAccess”,因为它不是“输入”的已知属性。

我使用的代码如下:

所有可能的尝试我都做了。任何人都知道我如何解决这个问题。

1.指令:HasAccessDirective.ts

@Directive({
  selector: '[appHasAccess]',
})

export class HasAccessDirective {

accessDetail = { 'a': 1 }
 @Input('appHasAccess') set appHasAccess(accessDetail: any) {
    // Based on right control enable/disable
    this.eleRef.nativeElement.disabled = this.appRights.hasRights(accessDetail);
}
constructor(private eleRef: ElementRef,
    private appRights: MyService) { }
}
Run Code Online (Sandbox Code Playgroud)

2.模块:DigiUserRightsModule.ts

   @NgModule({
        declarations: [
            HasAccessDirective
        ],
        imports: [
            CommonModule,
            HttpClientModule,
        ],
        exports: [
            HasAccessDirective
        ],
        providers: [UserRightsService]
    })

export class DigiUserRightsModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: DigiUserRightsModule,
            providers: [UserRightsService]
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

angularjs-directive angular angular-library angular5

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

将动态生成的输入字段连接到 mat-autocomplete

我允许用户动态创建输入字段。对于每个输入字段,我想将其连接到不同的 mat-autocomplete,以便它们彼此独立工作。我在这里遇到了障碍,因为我无法动态创建将自动完成连接到输入的元素引用(此处为#auto)。我该如何实现这一目标?

<div
  class="row"
  *ngFor="let field of getControls('requestFields'); let i = index"
  formArrayName="requestFields"
>
  <ng-container [formGroupName]="i">
    <div class="col-md-4">
      <mat-form-field class="example-full-width">
        <input
          type="text"
          placeholder="Name"
          matInput
          formControlName="reqName"
          matAutocomplete="auto"
        />
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option
            *ngFor="let option of (filteredColumns | async)"
            [value]="option"
          >
            {{ option }}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </div>
    <div class="col-md-2">
      <div class="togglebutton">
        <label>
          <span>Optional</span>
          <input type="checkbox" formControlName="reqOption" />
          <span class="toggle"></span>
        </label>
      </div>
    </div>
    <div class="col-md-4">
      <mat-form-field>
        <input
          matInput
          formControlName="reqValidations"
          placeholder="Validation"
          type="text"
        />
      </mat-form-field>
    </div>
  </ng-container>
</div>
Run Code Online (Sandbox Code Playgroud)

angular-material angular5 mat-autocomplete

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

从 Angular 6 服务中绑定图像

我有一个端点,它根据某些参数为我提供图像。这不是一个图像网址,而是一个普通图像。因此,当我到达邮递员中的端点时,作为响应,我收到一张图像(JPG)。

我是否可以在变量中接收该图像并将其绑定到 HTML 标签中?

所有问题都有将图像 url 映射到图像的解决方案,而我的是必须在 UI 中显示的图像。

显示图像组件.ts

this.appservice.getImage().subscribe((image) => {
    console.log(image);
 }
)
Run Code Online (Sandbox Code Playgroud)

服务.ts

getImg() {

 return this.httpClient.get('xyz.com', {headers: this.httpHeaders});

 }
Run Code Online (Sandbox Code Playgroud)

我应该如何在 HTML 上显示图像变量中收到的图像?

html javascript angular angular5 angular6

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

如何在应用程序首次加载时显示登录组件而不是 Angular 5 中的 appComponent

我对 Angular 5 完全陌生,我想在应用程序打开时显示登录页面。

现在我显示 appComponent,它有工具栏和侧面导航栏。但是当用户加载应用程序时,如果登录成功,我想显示登录屏幕,那么只有用户应该允许查看主页。

如果我将我的应用程序组件作为登录组件,我无法根据用户的菜单选择在主页中加载不同的组件。

应用程序组件.html

<mat-sidenav-container fullscreen>
    <mat-sidenav #sidenav class="app-sidenav">
        <mat-nav-list>
            <a mat-list-item routerLink="/home" routerLinkActive="active-list-item">
                <h2 matLine>Home</h2>
                <mat-icon matListIcon>home</mat-icon>
            </a>
            <a mat-list-item routerLink="/account" routerLinkActive="active-list-item">
                <h2 matLine>Account</h2>
                <mat-icon matListIcon>person</mat-icon>
            </a>
            <a mat-list-item routerLink="/settings" routerLinkActive="active-list-item">
                <h2 matLine>Settings</h2>
                <mat-icon matListIcon>settings</mat-icon>
            </a>
        </mat-nav-list>
    </mat-sidenav>
    <mat-sidenav-content>
        <mat-toolbar color="primary" class="mat-elevation-z3">
            <button mat-icon-button (click)="sidenav.toggle()">
        <mat-icon>menu</mat-icon>
      </button>
      My App
    </mat-toolbar>
    <div class="app-content">
      <router-outlet></router-outlet>  // router-outlet
    </div>
  </mat-sidenav-content>
</mat-sidenav-container>
Run Code Online (Sandbox Code Playgroud)

目前,当我运行应用程序时,正在加载此页面。我想显示全屏登录页面,而不是首先显示主页。

const  routings: Routes = [
    {path:'',redirectTo:'/app-root',pathMatch:'full'},
    {path:'home',component:HomeComponent},
    {path:'account',component:AccountComponent},
    {path:'settings',component:SettingsComponent},
    {path:'**',redirectTo:'/app-root',pathMatch:'full'},
];
Run Code Online (Sandbox Code Playgroud)

目前,当 url 为 ' ' …

typescript angular2-routing angular-components angular5

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

响应中的 HTTP 拦截器在 Angular 5 中不起作用

我希望如果任何 api 返回 401 错误响应,用户就会自动注销。为此,我拦截每个请求,一旦错误代码出现 401,我就会清除本地存储中的 jwt 令牌,并且身份验证防护会阻止但是在实现拦截器之后(这方面的示例非常少,并且文档中也没有提及),我无法命中任何 HTTP 请求。下面是我的代码。提前致谢。

import { Injectable, Injector } from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

    constructor() {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request).do((event: HttpEvent<any>) => {
        }, (err: any) => {
            if (err instanceof HttpErrorResponse) {
                // do error handling here
                console.log('and the error is ');
                console.log(err)
            }
        });
    } …
Run Code Online (Sandbox Code Playgroud)

angular-http-interceptors angular5

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