반응형

The specified command ("completion") is invalid. For a list of available options,
run "ng help".

 

터미널을 열었는데 위와같은 오류가 표시됩니다. 

 

해결 방법

사용하는 터미널에 따라서 ~/.bashrc 또는 zshell ~/.zshrc 등에 파일에 "source <(ng completion script)" 부분을 주석처리 해줍니다.

# source <(ng completion script)

 

다만, Angular의 자동 완성 기능을 잃게 된다고 합니다.

 

반응형

'Angular > Angular Tip' 카테고리의 다른 글

[ Angular ] .gitignore .angular 폴더 .cache 폴더  (0) 2022.07.05
반응형

.HTML

<input type="text" [(ngModel)]="id" (keyup)="check('id')" (keydown)="keyCheck(id)" [maxlength]="12" />

가장먼저 실행되고, 길게 눌렀을때 연속적으로 실행하는 keydown을 사용했습니다.

keypress는 영어나 숫자로 변경해서 입력 할 때까지 적용되지 않고, keyup은 한글 완성이 되지 않았을 경우 남게 됩니다.

 

keydown, keypress, keyup 비교 확인하기

 

.TS

keyCheck(e: any) {
    const exptext = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/;
    console.log(exptext.test(this.id));
    if(exptext.test(this.id)) {
      this.id = this.id.replace(exptext, '');
    }
}

 

정규식

// 영어만
const eng = /^[a-zA-Z]*$/;

// 숫자만
const num = /^[0-9]*$/;

// 영어 + 숫자
const engNum =  /^[a-zA-Z0-9]*$/;

// 이메일
const email = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+$/;

// 핸드폰
const phone = /^\d{2,3}-\d{3,4}-\d{4}$/;

// 주민등록번호
const resident = /\d{6} \- [1-4]\d{6}/;

// 8자리 이상 영문 + 숫자 + 특수문자 조합
const password = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/;

 

반응형
반응형

 

 

Angular에서 용량 제한을 걸어둔 내용입니다.

 

angular.json

"budgets": [
    {
      "type": "initial",
      "maximumWarning": "4mb",
      "maximumError": "5mb"
    },
    {
      "type": "anyComponentStyle",
      "maximumWarning": "4mb",
      "maximumError": "5mb"
    }
],

initial 용량만 늘려주면 된다는 말이 있는데, initial만 늘려주고도 빌드부분에서 같은 내용이 나와서 anyComponentStyle 부분에도 추가시켜 주었습니다.

반응형
반응형

ADD : Boolean 값에 따라 class 적용

<div [ngClass]="{ 'abc': check, 'bbb': !check }">안녕하세요</div>
<div [class.ccc]="check">안녕히계세요</div>

 

ADD : Multiple class 적용

<div [ngClass]="{'abc bbb': check}">안녕하세요</div>
<div [ngClass]="{abc: check, bbb: check2, ccc:check3}">안녕히계세요</div>

 

ADD : 3항 연산자에 class 적용 [ 왼쪽(abc) : true일 때 적용, 오른쪽(bbb) : false일 때 적용 ]

<div [ngClass]="check ? 'abc' : 'bbb'">안녕하세요</div>

 

ADD : 함수 호출 적용

<div [ngClass]="checked('type')">안녕하세요</div>
checked(list: String) {
    let className = '';
    if(list === 'type') {
      className = 'abc';
    }
    // 리턴할 클래스 이름
    return className;
}

 

반응형
반응형

npm install

 

NodeJS

$ npm install express
$ npm install mongoose
$ npm install body-parser
$ npm install cookie-parser
$ npm install cors

 

 

Angular 작성하기

 

app.component.html

<input type="text" [(ngModel)]="id" placeholder="아이디를 입력해주세요." autocomplete="off" />

<a href="javascript:void(0)" (click)="login()">로그인</a>

 

app.component.ts

export class AppComponent implements OnInit {
    id: String = '';
    
    login() {
        const req = {
            id: this.id,
            password: this.password
        };
        this.userService.login(req)
        .subscribe(res => {});
    }
}

 

 

NodeJS 작성하기

 

app.js

const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);

const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const cors = require('cors');

// parser
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// cors Error
app.use(cors({
    "origin": "*"
  }
));

// router
app.use('/user', require("./controllers/userController"));

// server 실행
const port = 3000;
server.listen(port, () => {
    const message = `
        [ new project server ]
        Running Port : localhost:${port}
        Start Time : ${Date()}
    `;
    console.log(message);
});

module.exports = app;

 

userController.js

const express = require("express");
const router = express.Router();

router.post('/login', function(req, res, next) {
    let query = req.body;
    console.log(query);
    console.log('로그인 들어옴');
});

module.exports = router;
반응형
반응형

.gitignore 추가 관련

/.angular
/.angular/
.angular
.angular/cache
/.angular/cache
/.cache
/.cache/babel-webpack

 

.gitignore가 작동하지 않을 경우

$ git rm -r --cached .

$ git add .

$ git commit -m 'Fix Commit'

$ git push

 

 

 


Angular 홈페이지 내용

$ ng config cli.cache.environment all

$ ng config cli.cache.path ".cache/ng"

Angular 홈페이지 바로가기

 

 

반응형
반응형

Font Awesome 바로가기

 

npm / add

$ npm install @fortawesome/fontawesome-svg-core@1.2.36
$ npm install @fortawesome/free-solid-svg-icons@5.15.4
$ npm install @fortawesome/angular-fontawesome@0.11.1

$ ng add @fortawesome/angular-fontawesome

 

app.module.ts

import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';

@NgModule({

    ...
    
    imports: [
        FontAwesomeModule
    ],
})

 

app.component.ts

import { faYoutube } from '@fortawesome/free-brands-svg-icons';
// import { faBell } from '@fortawesome/free-solid-svg-icons';
import { faBell } from '@fortawesome/free-regular-svg-icons';

...

export class AppComponent implements OnInit {
  faYoutube = faYoutube;
  faBell = faBell;

  constructor() { }

  ngOnInit(): void {
  }

}

폰트어썸 사이트에서 아이콘을 클릭해보면 아래와 같이 class 이름이 나옵니다. 그리고 위 코드를 보면 import한 부분에 "import { faBell } from '@fortawesome/free-regular-svg-icons';"에서 "from '@fortawesome/free-regular-svg-icons'" 부분이 fa-reular 아이콘들을 가져왔다고 보면 되고,  "faBell"부분이 벨 아이콘을 가져왔다고 생각하면 편합니다.

Font Awesome ICON

 

app.component.html

<fa-icon [icon]="faYoutube" style="font-size: 40px;"></fa-icon>
<fa-icon [icon]="faBell" style="font-size: 40px;"></fa-icon>

이렇게 불러주면 아이콘을 가져다 사용할 수 있습니다.

 

반응형
반응형

에러 내용

Error: node_modules/@angular/material/core/index.d.ts:794:21 - error TS2694: Namespace '"/Users/junhyeok/project/new/new-project/node_modules/@angular/core/core"' has no exported member 'ɵɵFactoryDeclaration'.

794     static ɵfac: i0.ɵɵFactoryDeclaration<MatRipple, [null, null, null, { optional: true; }, { optional: true; }]>;

 

Error: ./src/main.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Unknown import type?
    at Object.reflectTypeEntityToDeclaration (/Users/junhyeok/project/new/new-project/node_modules/@angular/compiler-cli/src/ngtsc/reflection/src/typescript.js:448:23)
    at /Users/junhyeok/project/new/new-project/node_modules/@angular/compiler-cli/src/ngtsc/metadata/src/util.js:34:35
    at Array.map (<anonymous>)
    at Object.extractReferencesFromType (/Users/junhyeok/project/new/new-project/node_modules/@angular/compiler-cli/src/ngtsc/metadata/src/util.js:29:29)

 

호환문제 ?

 

문제 이유

angular version 문제라고 합니다.

angular v11 에서 angular v14로 업그레이드

 

공식 홈페이지에서 하라던 내용

$ ng update @angular/core@12 @angular/cli@12

CLI 버전이 오래되어서 업데이트 하라던 내용인것 같습니다.

 

 

해결 방법

$ npm install -g npm-check-updates

$ ncu -u

$ npm install

버전이 호환되지 않아서 그랬던 내용인것 같습니다.

버전이 올라가면서 옛날 버전과는 호환이 되지 않았던 것인듯 싶습니다. 

새로운 프로젝트를 할 때는 항상 최신 버전으로 하는 방향으로 생각해야 할 듯 합니다.

 

반응형

'Angular > Angular' 카테고리의 다른 글

[ Angular ] 서버로 전달하기 [ NoSQL ]  (1) 2022.07.07
[ Angular ] font-awesome 사용하기  (1) 2022.06.28
[ Angular ] @Output 사용법  (0) 2022.06.23
[ Angular ] @Input 사용법  (1) 2022.06.23
[ Angular ] font 사용하기  (0) 2022.06.21
반응형

부모 컴포넌트로 데이터 전달하기 [ @Output() ]

자식 컴포넌트 / 디렉티브에 @Output() 데코레이터를 사용하면 부모 컴포넌트 / 디렉티브로 데이터를 전달할 수 있습니다.

 

@Output()

  • @Output() 데코레이터는 자식 컴포넌트 프로퍼티 중 부모 컴포넌트로 데이터를 보내는 프로퍼티를 지정하는 역할을 합니다.
  • 이벤트를 발생시키기 위해서 @Output() 데코레이터는 반드시 EventEmitter 프로퍼티에 선언해야 합니다.

 

자식 컴포넌트 ( Child Component.ts )

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

export class PHeaderComponent implements OnInit {
  @Output() newItemEvent = new EventEmitter<any>();

  addNewItem(value: any) {
    this.newItemEvent.emit(value);
  }
}

 

자식 컴포넌트 ( Child Component.html )

<!--
1. 헤더 리스트를 만들기 위한 내용
2. click 이벤트를 발생시킬때마다 부모 컴포넌트에 영향을 주기위한 내용
-->
<ul class="header_list">
    <li (click)="addNewItem(i + 1)" *ngFor="let list of [0, 1, 2, 3, 4, 5]; let i = index;" id="parasite{{i + 1}}" [ngClass]="list + 1 === headerValue ? 'active' : ''">Menu {{i + 1}}</li>
</ul>

 

 

 

부모 컴포넌트 ( Parent Component.ts )

addItem(e: any) {
    console.log(e);
}

 

부모 컴포넌트 ( Parent Component.html )

<app-p-header (newItemEvent)="addItem($event)"></app-p-header>

 

반응형
반응형

자식 컴포넌트로 데이터 전달하기 [ @Input() ]

@Input() 데코레이터는 자식 컴포넌트 / 디렉티브에 있는 특정 프로퍼티가 부모 컴포넌트 / 디렉티브에서 값을 받는다는 것을 지정하는 데코레이터입니다.

@Input()

  • @Input() 데코레이터는 부모 - 자식 관계에서만 사용할 수 있습니다.

 

자식 컴포넌트 ( Child Component.ts )

import { Component, OnInit, Input } from '@angular/core';

export class PHeaderComponent implements OnInit {
    @Input() item: any;
    
    ngOnInit(): void {
        console.log(this.item);
    }
}

 

자식 컴포넌트 ( Child Component.html )

<h1>
    <em>{{item[0]}}</em> {{item[1]}}
</h1>

 

 

 

부모 컴포넌트 ( Parent Component.ts )

export class ParallaxComponent implements OnInit {
    currentItem: any = ['Parallax Site', '(패럴랙스 사이트)'];
}

@Input() 데코레이터를 사용하면 부모 컴포넌트의 currentItem 프로퍼티 값이 자식 컴포넌트 item 프로퍼티로 전달되기 때문에, 자식 컴포넌트 템플릿에 정의된 대로 ['Parallax Site', '(패럴랙스 사이트)']라는 배열 값이 렌더링 됩니다.

 

부모 컴포넌트 ( Parent Component.html )

<app-p-header [item]="currentItem"></app-p-header>

부모 컴포넌트에서 currentItem 값을 할당해 줍니다.

반응형

+ Recent posts